【问题标题】:C# - Dll-Plugin and Entity-FrameworkC# - Dll 插件和实体框架
【发布时间】:2016-09-05 13:07:17
【问题描述】:

我正在使用 PluginManager 搜索 dll 文件并将它们(和她的函数)添加到我当前的应用程序中。

我也使用实体框架从对象创建数据库和表,但我必须在 DatabaseContext 类中为数据库声明对象。

如何将插件中的一些对象保存到此数据库中?

我试过这个:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        foreach( PluginDto plugin in BackendContext.Current.PluginManager._plugins) {
            foreach(Type obj in plugin.plugin.getPluginDatabaseObjects())
            {
                Type typ = typeof(EntityTypeConfiguration<>).MakeGenericType(obj);

                List<MethodInfo> l = modelBuilder.GetType().GetMethods().ToList<MethodInfo>();

                MethodInfo m_Entitiy = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(new Type[] { obj });
                var configObj = m_Entitiy.Invoke(modelBuilder, null);

                MethodInfo m_ToTable = configObj.GetType().GetMethod("ToTable", new Type[] { typeof(String) });
                m_ToTable.Invoke(configObj, new object [] { obj.Name });
            }
        }
    }

但是得到这个异常:

EntityFramework.dll 中出现“System.InvalidOperationException”类型的未处理异常

附加信息:支持“DatabaseContext”上下文的模型自数据库创建以来已更改。考虑使用 Code First 迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)。

【问题讨论】:

  • 你看this了吗?
  • @bsoulier 我试过这个:并得到这个错误:“实体类型字段不是当前上下文模型的一部分。”
  • 根据这个错误好像EF不能真正做动态表,检查here
  • @bsoulier 我认为你是对的!你知道可以处理这个问题的好选择吗?

标签: c# entity-framework dll plugins


【解决方案1】:

EF 可以支持使用此following example 添加动态 DBSet。

这个想法是,不是在 Db 上下文上手动创建 DbSet,而是重载 OnModelCreating 方法,该方法允许动态构建类型。

请记住,此示例采用自定义属性 PersistentAttribute,用于注释类,以便此代码找出哪些类适合模型生成。

【讨论】:

  • 这个工作正常,但是当我添加一个新类时它失败了
  • 这与 EF 代码首先必须更新其表以持久化模型有关,如文章底部所示,每次添加/更新实体时不要忘记更新模型
  • 我试过了!但我不能让它工作......你能给我举个小例子吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
相关资源
最近更新 更多