Last active
December 30, 2016 15:26
-
-
Save Kimserey/f879806c1b699235228384e11d35c011 to your computer and use it in GitHub Desktop.
Helper base class to facilitate crud operations with sqlite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RepositoryResult<T> | |
{ | |
public T Result { get; set; } | |
public bool IsSuccess { get; set; } | |
public string ErrorMessage { get; set; } | |
} | |
using System; | |
using SQLite; | |
namespace Storage | |
{ | |
public class RepositoryBase | |
{ | |
string _dbPath; | |
public RepositoryBase(string dbPath) | |
{ | |
_dbPath = dbPath; | |
EnsureTableExist(); | |
} | |
public void EnsureTableExist() | |
{ | |
using (var conn = GetConnection()) | |
{ | |
conn.CreateTable<XXX>(); | |
} | |
} | |
public SQLiteConnection GetConnection() | |
{ | |
// Store datetime as ticks, recommended in SQLite source code. | |
return new SQLiteConnection(_dbPath); | |
} | |
protected bool Add(object item) | |
{ | |
using (var con = GetConnection()) | |
{ | |
var result = con.Insert(item); | |
return result == 1; | |
} | |
} | |
public bool Delete(int id) | |
{ | |
using (var con = GetConnection()) | |
{ | |
var result = con.Delete<RecipeSqlite>(id); | |
return result == 1; | |
} | |
} | |
public bool Update(object item) | |
{ | |
using (var con = GetConnection()) | |
{ | |
var result = con.Update(item); | |
return result == 1; | |
} | |
} | |
public RepositoryResult<T> GenericResult<T>(string id, Func<T> generator, Func<bool> execute) | |
{ | |
if (execute()) | |
return new RepositoryResult<T> | |
{ | |
ErrorMessage = null, | |
IsSuccess = true, | |
Result = generator() | |
}; | |
return new RepositoryResult<T> | |
{ | |
ErrorMessage = String.Format("Operation failed [{0}]", id), | |
IsSuccess = false | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment