I have installed SQLite-net-pcl package in my project. And now I want to use it for simple CRUD operations. The thing is that all the documentation I read was confusing to me. Can anyone hint me for the proper steps to perform a CRUD operation in Xamarin.Forms to accept a value form Entry and store it in database?
-
Have you tried this: developer.xamarin.com/guides/xamarin-forms/… ? Because this documentation is very good to start. I suggest you to try the guide above and update your original post with any problem you encounter.pinedax– pinedax2017-05-23 06:17:28 +00:00Commented May 23, 2017 at 6:17
-
There are tons of tutorials in the web. Here you have another one: code.tutsplus.com/tutorials/… Try these first, and then come back to SO, when you have a specific problemJoehl– Joehl2017-05-23 06:19:20 +00:00Commented May 23, 2017 at 6:19
Add a comment
|
1 Answer
I use this method in my working app.
Install SQLite-net-pcl
I use async methods. To exclude locks, I use this class:
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(); } } }Create domains(tables):
//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;} ...... }Create repository:
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 }Create static field for DataRepository in your App class. Use this App.Repo in your code.
App.Repo.Save(new Data { ... }) ;
This is a simplified example of use.