0

Xamarin Forms という新しいプラットフォームを試してみました。.Net Core と EF Core の知識に基づいて、Visual Studio 2019 に含まれる Xamarin Forms Shell テンプレートに Sqlite ORM サービス (sqlite-net-pcl) を挿入することから始めることにしました。このテンプレートには、に基づく Mock CRUD サービスが既に実装されています。メモリ データ構造を変更したので、独自のサービスを実装して DependencyService を挿入したいと考えました。最初に、必要な属性でデータ モデルを変更しました。

public class Item
{
    [PrimaryKey, AutoIncrement]
    public string Id { get; set; }
    public string Text { get; set; }
    public string Description { get; set; }
}

次に、CRUD サービスを実装しました。

public class SqliteDataStore : IDataStore<Item>
{
    private readonly SQLiteConnection _db;

    public SqliteDataStore()
    {
        _db = new SQLiteConnection(Path.Combine(FileSystem.AppDataDirectory, "items.sqlite"));
        _db.CreateTable<Item>();
        if (_db.Table<Item>().Count().Equals(0))
        {
            _db.InsertAll(new List<Item>
            {
                new Item { Id = Guid.NewGuid().ToString(), Text = "First item", Description = "This is the first item description." },
                new Item { Id = Guid.NewGuid().ToString(), Text = "Second item", Description = "This is the second item description." },
                new Item { Id = Guid.NewGuid().ToString(), Text = "Third item", Description = "This is the third item description." }
            }
            );
        }
    }

    public async Task<bool> AddItemAsync(Item item)
    {
        _db.Insert(item);
        return await Task.FromResult(true);
    }

    public async Task<bool> DeleteItem(string id)
    {
        _db.Delete<Item>(id);
        return await Task.FromResult(true);
    }

    public async Task<Item> GetItemAsync(string id)
    {
        return await Task.FromResult(_db.Get<Item>(id));
    }

    public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(_db.Table<Item>().ToList());
    }

    public async Task<bool> UpdateItemAsync(Item item)
    {
        _db.Update(item);
        return await Task.FromResult(true);
    }
}

次に、App クラスで挿入されたサービスを変更しました。

public App()
{
    InitializeComponent();

    DependencyService.Register<SqliteDataStore>();
    MainPage = new AppShell();
}

この実装は、Xamarin Forms の EF Core で適切に動作しますが、EF Core は非常に遅いため、ORM (sqlite-net-pcl) を変更しましたが、動作しません。

4

1 に答える 1