iT邦幫忙

2022 iThome 鐵人賽

DAY 16
0
Software Development

30天學習.Net MAUI系列 第 16

16.實作Todo (一)

  • 分享至 

  • xImage
  •  

我們今天先將sqlite套件加入我們的專案中

在我們的Todo專案右鍵選取打開套件
https://ithelp.ithome.com.tw/upload/images/20221001/20108931oOJs9qHtT6.png

搜尋sqlite
https://ithelp.ithome.com.tw/upload/images/20221001/201089310oe0KQfJiD.png

我們這邊使用的是SQLitePCLRaw

SQLitePCLRaw 是一個可移植類庫 (PCL)並可用於多平台,並對 SQLite 進行原始訪問

找到這些套件,並點擊安裝
sqlite-net-pcl
SQLitePCLRaw.bundle_green
SQLitePCLRaw.core
SQLitePCLRaw.provider.dynamic_cdecl
SQLitePCLRaw.provider.sqlite3

https://ithelp.ithome.com.tw/upload/images/20221001/20108931cOMDvLcPRI.png

接著我們創建一個新資料夾model並添加TodoItemModel.cs
https://ithelp.ithome.com.tw/upload/images/20221001/20108931uia7N3pBX3.png

TodoItemModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Todo.Models
{
    public class TodoItemModel
    {
        public int TodoId { get; set; }
        public string Title { get; set; }
        public bool IsDone { get; set; }
    }
}

接著,我們創建services資料夾並且創建介面ITodoService與服務TodoService

ITodoService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public interface ITodoService
    {
        Task<List<TodoItemModel>> GetTodos();
        Task<int> AddTodo(TodoItemModel todoItemModel);
        Task<int> DeleteTodo(TodoItemModel todoItemModel);
        Task<int> UpdateTodo(TodoItemModel todoItemModel);
    }
}

TodoService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public class TodoService : ITodoService
    {
        public Task<int> AddTodo(TodoItemModel todoItemModel)
        {
            throw new NotImplementedException();
        }

        public Task<List<TodoItemModel>> GetTodos()
        {
            throw new NotImplementedException();
        }

        Task<int> ITodoService.DeleteTodo(TodoItemModel todoItemModel)
        {
            throw new NotImplementedException();
        }

        Task<int> ITodoService.UpdateTodo(TodoItemModel todoItemModel)
        {
            throw new NotImplementedException();
        }
    }
}

在service裡面加入創建db方法

namespace Todo.Services
{
    public class TodoService : ITodoService
    {
        private SQLiteAsyncConnection _connection;

        public TodoService()
        {
            _setDb();
        }

        private async void _setDb()
        {
            if (_connection == null) {
                string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "db.sqlite");
                _connection = new SQLiteAsyncConnection(dbPath);
                await _connection.CreateTableAsync<TodoItemModel>();
            }
        }


        public Task<int> AddTodo() {
			...
		

接著來實作方法

		...

        public Task<int> AddTodo(TodoItemModel todoItemModel)
        {
            return _connection.InsertAsync(todoItemModel);
        }

        public async Task<List<TodoItemModel>> GetTodos()
        {
            var todos = await _connection.Table<TodoItemModel>().ToListAsync();
            return todos;
        }

        Task<int> ITodoService.DeleteTodo(TodoItemModel todoItemModel)
        {
            return _connection.DeleteAsync(todoItemModel);
        }

        Task<int> ITodoService.UpdateTodo(TodoItemModel todoItemModel)
        {
            return _connection.UpdateAsync(todoItemModel);
        }
		
		...

接著,我們回到MauiProgram.cs將我們的service加入:
builder.Services.AddSingleton<ITodoService, TodoService>();

MauiProgram.cs

using Todo.Services;

namespace Todo;

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

		// Add TodoItem Service
		builder.Services.AddSingleton<ITodoService, TodoService>();

		return builder.Build();
	}
}

今天先完成與我們的db做連接,並且實現功能,明天接著測試功能並將資料綁定到MAUI的view上


Todo\Services\ITodoService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public interface ITodoService
    {
        Task<List<TodoItemModel>> GetTodos();
        Task<int> AddTodo(TodoItemModel todoItemModel);
        Task<int> DeleteTodo(TodoItemModel todoItemModel);
        Task<int> UpdateTodo(TodoItemModel todoItemModel);
    }
}

Todo\Services\TodoService.cs

using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Todo.Models;

namespace Todo.Services
{
    public class TodoService : ITodoService
    {
        private SQLiteAsyncConnection _connection;

        public TodoService()
        {
            _setDb();
        }

        private async void _setDb()
        {
            if (_connection == null) {
                Console.WriteLine("Creating New db");
                string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "db.sqlite");
                _connection = new SQLiteAsyncConnection(dbPath);
                await _connection.CreateTableAsync<TodoItemModel>();
            }
            Console.WriteLine("Already setting db");
        }


        public Task<int> AddTodo(TodoItemModel todoItemModel)
        {
            return _connection.InsertAsync(todoItemModel);
        }

        public async Task<List<TodoItemModel>> GetTodos()
        {
            var todos = await _connection.Table<TodoItemModel>().ToListAsync();
            return todos;
        }

        Task<int> ITodoService.DeleteTodo(TodoItemModel todoItemModel)
        {
            return _connection.DeleteAsync(todoItemModel);
        }

        Task<int> ITodoService.UpdateTodo(TodoItemModel todoItemModel)
        {
            return _connection.UpdateAsync(todoItemModel);
        }
    }
}

Todo\MauiProgram.cs

using Todo.Services;

namespace Todo;

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

		// Add TodoItem Service
		builder.Services.AddSingleton<ITodoService, TodoService>();

		return builder.Build();
	}
}

上一篇
15.關於Data binding (二)
下一篇
17.實作Todo (二)
系列文
30天學習.Net MAUI30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言