【问题标题】:Entity framework data provider for LiteDBLiteDB 的实体框架数据提供者
【发布时间】:2020-02-26 19:18:00
【问题描述】:

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

【问题讨论】:

    标签: entity-framework litedb


    【解决方案1】:

    您的问题非常相关。 LiteDB 有一个与 EntityFramework 非常相似的 API。在我看来,我认为没有必要将 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 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);
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2013-11-11
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多