Maui blazor与sqlite开发一个增删改查

在android端增删改不能运行。也看不出来是什么,但运行到windows可以运行。

Maui blazor与sqlite开发一个增删改查_第1张图片

引入sqlite-net-pcl 开发Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
namespace MauiAppBlazorapp.Model
{
    internal class TaskJob
    {

        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        public DateTime Date { get; set; }
        public string  TaskName { get; set; }
        public Boolean FinishedFlag { get; set; }

        [SQLite.MaxLength(4000)]
        public string Summary { get; set; }

    }
}

TaskjobService.cs 定义增删改查:

using MauiAppBlazorapp.Model;
using SQLite;

namespace MauiAppBlazorapp.Service
{
    internal class TaskjobService
    {
        private string _dbPath;
        public string StatusMessage { get; set; }
        private SQLiteAsyncConnection conn;

        public TaskjobService(string dbPath)
        {
            _dbPath = dbPath;
        }

        private async Task InitAsync()
        {
            // Don't Create database if it exists
            if (conn != null)
                return;
            // Create database and WeatherForecast Table
            conn = new SQLiteAsyncConnection(_dbPath);
            await conn.CreateTableAsync<TaskJob>();
        }

        public async Task<List<TaskJob>> GetJobAsync()
        {
            await InitAsync();
            return await conn.Table<TaskJob>().ToListAsync();
        }

        public async Task<TaskJob> CreateJobAsync( TaskJob taskjob)
        {
            // Insert
            await conn.InsertAsync(taskjob);
            // return the object with the
            // auto incremented Id populated
            return taskjob;
        }

        public async Task<TaskJob> UpdateJobAsync(TaskJob taskjob)
        {
            // Update
            await conn.UpdateAsync(taskjob);
            // Return the updated object
            return taskjob;
        }

        public async Task<TaskJob> DeleteJobAsync(
            TaskJob taskjob)
        {
            // Delete
            await conn.DeleteAsync(taskjob);
            return taskjob;
        }

    }
}

同时在MauiProgram.cs加入数据库的链接:

using MauiAppBlazorapp.Service;
using Microsoft.Extensions.Logging;

namespace MauiAppBlazorapp
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                });

            builder.Services.AddMauiBlazorWebView();

#if DEBUG
    		builder.Services.AddBlazorWebViewDeveloperTools();
    		builder.Logging.AddDebug();
#endif

            //builder.Services.AddSingleton();
            // Set path to the SQLite database (it will be created if it does not exist)
            var dbPath =
                Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    @"Taskjob.db");
            // Register WeatherForecastService and the SQLite database
            builder.Services.AddSingleton<TaskjobService>(
                s => ActivatorUtilities.CreateInstance<TaskjobService>(s, dbPath));
            return builder.Build();
        }
    }
}

相关的TaskjobList.razor代码:引入@using MauiAppBlazorapp.Model
注入服务 @inject Service.TaskjobService Taskserice @code里的代码以前以为是typescript 现在看来是C#

@page "/taskList"
@using MauiAppBlazorapp.Model
@inject Service.TaskjobService Taskserice
<h1>任务例表</h1>
<p style="color:red">@Error</p>
@if (tasklists == null)
{
    <p><em>无任务...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>时间</th>
                <th>工作</th>
                <th>完成</th>
                <th>说明</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in tasklists)
            {
                <tr>
                    <td>@item.Date.ToShortDateString()</td>
                    <td>@item.TaskName</td>
                    <td>
                        <!-- 将 Switch 替换为 Checkbox -->
                        <input type="checkbox" @bind="item.FinishedFlag" />
                    </td>
                    <td>@item.Summary</td>
                    <td>
                        <button class="btn btn-primary" @onclick="(() => EditTask(item))"> 修改 </button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <p>
        <button class="btn btn-success" @onclick="AddNewTask"> 增加任务 </button>
    </p>
    @if (ShowPopup)
    {
        <div class="modal" tabindex="-1" style="display:block" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">修改任务</h3>
                        <button type="button" class="close" @onclick="ClosePopup">
                            <span aria-hidden="true">X</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="taskName">任务</label>
                            <input class="form-control" type="text" id="taskName" @bind="objtask.TaskName" />
                        </div>
                        <div class="form-group">
                            <label>完成</label>
                            <!-- 将 Switch 替换为 Checkbox -->
                            <input type="checkbox" @bind="objtask.FinishedFlag" />
                        </div>
                        <div class="form-group">
                            <label for="summary">说明</label>
                            <input class="form-control" type="text" id="summary" @bind="objtask.Summary" />
                        </div>
                        <button class="btn btn-success" @onclick="SaveTask">保存</button>
                        @if (objtask.Id > 0)
                        {
                            <button class="btn btn-danger" @onclick="DeleteTask">删除</button>
                        }
                    </div>
                </div>
            </div>
        </div>
    }
}

@code
{
    string Error = "";
    List<TaskJob> tasklists = new List<TaskJob>();
    TaskJob objtask = new TaskJob();
    bool ShowPopup = false;
    protected override async Task OnInitializedAsync()
    {
        tasklists = await Taskserice.GetJobAsync();
    }
    void AddNewTask()
    {
        objtask = new TaskJob();
        objtask.Id = 0;
        ShowPopup = true;
    }
    void EditTask(TaskJob weatherForecast)
    {
        objtask = weatherForecast;
        ShowPopup = true;
    }
    void ClosePopup()
    {
        ShowPopup = false;
    }
    async Task SaveTask()
    {
        ShowPopup = false;
        Error = "";
        try
        {
            if (objtask.Id == 0)
            {
                TaskJob objTask = new TaskJob();
                objTask.Date = System.DateTime.Now;
                objTask.Summary = objtask.Summary;
                objTask.TaskName = objtask.TaskName;
                objTask.FinishedFlag = objtask.FinishedFlag;
                var NewWeatherForecast = await Taskserice.CreateJobAsync(objTask);
                tasklists.Add(NewWeatherForecast);
            }
            else
            {
                await Taskserice.UpdateJobAsync(objtask);
            }
        }
        catch (Exception ex)
        {
            Error = ex.Message;
        }
    }

    async Task DeleteTask()
    {
        ShowPopup = false;
        try
        {
            Error = "";
            await Taskserice.DeleteJobAsync(objtask);
            tasklists.Remove(objtask);
        }
        catch (Exception ex)
        {
            Error = ex.Message;
        }
    }
}

你可能感兴趣的:(net,开发,sqlite,数据库,maui,razor)