I want my entity framework Dbcontext class to work with different -2 databases. It is working fine with SQL Server, MySql, SQLite using respective data providers. But unable to get any data provider for LiteDB(no-sql).Is there any article or sample code regarding entity framework with LiteDB.
Your question is very relevant. LiteDB has an API very similar to EntityFramework. In my way of thinking I don't see the need to use EF with LiteDB. But that's just my way of thinking. Answering your question, there is still no compatibility implemented. Attached is the issue link.
Do you have plan to support for EntityFramework #1198 https://github.com/mbdavid/LiteDB/issues/1198
You can solve the problem by implementing a common database interface.
Like this:
public interface IDatabaseService<TEntity>
where TEntity : Entity, new()
{
void Insert(TEntity entity);
}
LiteDB (this class can be an abstract class to ensure that you don't instantiate by forgetting the SQL server database):
public class LiteDBService<TEntity> : IDatabaseService<TEntity>
where TEntity : Entity, new()
{
private string _stringConnection;
private LiteDatabase _db;
protected LiteCollection<TEntity> _collection;
public DatabaseService()
{
_stringConnection = string.Format("filename={0};journal=false", DependencyService.Get<IFileService>().GetLocalFilePath("LiteDB.db"));
_db = new LiteDatabase(_stringConnection);
_collection = _db.GetCollection<TEntity>();
}
public void Insert(TEntity entity)
{
_collection.Insert(entity);
}
}
SqlServer:
public class SQLServerService <TEntity> : LiteDBService<TEntity>, IDatabaseService<TEntity>
where TEntity : Entity, new()
{
private readonly MyContext _context;
public SQLServerService(MyContext context)
{
_context = context;
}
public void Insert(TEntity entity)
{
_context.Set<TEntity>.Add(entity);
_context.SaveChanges();
base.Insert(entity);
}
}