LiteDB 的实体框架数据提供程序

Vik*_*kas 5 entity-framework litedb

我希望我的实体框架 Dbcontext 类能够使用不同的 -2 数据库。它使用各自的数据提供程序与 SQL Server、MySql、SQLite 一起正常工作。但无法获取 LiteDB(no-sql)的任何数据提供程序。是否有任何有关 LiteDB 实体框架的文章或示例代码。

Fil*_*nio 6

你的问题非常相关。LiteDB 的 API 与 EntityFramework 非常相似。以我的想法,我不认为有必要将 EF 与 LiteDB 一起使用。但这只是我的想法。回答你的问题,仍然没有实现兼容性。附上问题链接。

您是否计划支持 EntityFramework #1198 https://github.com/mbdavid/LiteDB/issues/1198

您可以通过实现通用数据库接口来解决该问题。

像这样:

public interface IDatabaseService<TEntity>
        where TEntity : Entity, new()
{
    void Insert(TEntity entity);
}
Run Code Online (Sandbox Code Playgroud)

LiteDB(这个类可以是一个抽象类,以确保你不会因为忘记SQL Server数据库而实例化):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

数据库服务器:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)