LiteDB的Entity Framework数据提供程序

5

我希望我的实体框架DbContext类可以与不同的数据库相互配合。目前,使用各自的数据提供程序,它可以很好地与SQL Server、MySql、SQLite配合使用。但是我无法获取适用于LiteDB(no-sql)的任何数据提供程序。是否有关于使用实体框架与LiteDB相关的文章或示例代码可供参考。

1个回答

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);
}

LiteDB(这个类可以是抽象类,以确保您不会因忘记SQL服务器数据库而实例化):

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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接