我尝试为我尝试新平台 Xamarin Forms。基于 .Net Core 和 EF Core 知识,我决定首先在 Visual Studio 2019 中包含的 Xamarin Forms Shell 模板中注入 Sqlite ORM 服务 (sqlite-net-pcl)。在此模板中,已经实现了基于 in- 的 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),但它不起作用。