我已经在我的项目中安装了 SQLite-net-pcl 包。现在我想用它来进行简单的 CRUD 操作。问题是我读到的所有文档都让我感到困惑。谁能提示我在 Xamarin.Forms 中执行 CRUD 操作以接受值表单条目并将其存储在数据库中的正确步骤?
最佳答案
我在我的工作应用程序中使用此方法。
我使用异步方法。为了排除锁,我使用此类:
public sealed class AsyncLock { private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); private readonly Task<IDisposable> _releaser; public AsyncLock() { _releaser = Task.FromResult((IDisposable)new Releaser(this)); } public Task<IDisposable> LockAsync() { var wait = _semaphore.WaitAsync(); return wait.IsCompleted ? _releaser : wait.ContinueWith((_, state) => (IDisposable)state, _releaser.Result, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private sealed class Releaser : IDisposable { private readonly AsyncLock m_toRelease; internal Releaser(AsyncLock toRelease) { m_toRelease = toRelease; } public void Dispose() { m_toRelease._semaphore.Release(); } } }
创建域(表):
//base class for table public class Entity { [PrimaryKey, AutoIncrement] public int Id { get; set; } } //your table public class Data :Entity { public string Prop1 {get;set;} ...... } public class Data2 :Entity { public string Prop2 {get;set;} ...... }
创建存储库:
public class DataRepository { private SQLiteAsyncConnection _db; private static readonly AsyncLock Mutex = new AsyncLock(); public async Task CreateDatabaseAsync(string path) { using (await Mutex.LockAsync().ConfigureAwait(false)) { _db= new SQLiteAsyncConnection(path); await _db.CreateTableAsync<Data>(); //create other tables } public async Task Save<T>(T entity) where T : Entity, new() { using (await Mutex.LockAsync().ConfigureAwait(false)) { await _db.InsertAsync(entity); } } public async Task Delete(Entity item) { using (await Mutex.LockAsync().ConfigureAwait(false)) { await _db.DeleteAsync(item); } } public async Task Update<T>(T entity) where T : Entity, new() { using (await Mutex.LockAsync().ConfigureAwait(false)) { await _db.UpdateAsync(entity); } } ........ //other base method }
在您的 App 类中为 DataRepository 创建静态字段。用这个 代码中的 App.Repo。
App.Repo.Save(new Data { ... }) ;
这是一个简化的使用示例。
关于c# - 如何在xamarin表单中使用SQLite-Net-PCL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127032/