【问题标题】:Add entity types after model creation in DbContext在 DbContext 中创建模型后添加实体类型
【发布时间】:2018-10-20 20:00:28
【问题描述】:

我正在使用 EF Core 2,并尝试将实体动态添加到模型中。 场景是:

  1. 用户在 Web 应用程序中创建具有自定义属性的实体

  2. 我在运行时创建了一个映射此实体的类(请参阅How to emit a Type in .NET Core

  3. 我在db上下文的OnModelCreating方法中将创建的类添加到模型中(见https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/

一切正常,除非我想在创建新实体的同一请求(API 调用)中向数据库写入新创建类的新实例。

这是因为DbContext 的范围是请求(不是瞬态的),所以DbContext 在我有机会创建新实体之前调用了OnModelCreating 方法。

这是我得到的错误:

The entity type 'People' was not found. 
Ensure that the entity type has been added to the model.

关于如何实现这一点的任何建议?我认为不可能按需调用OnModelCreating,而且我找不到访问上下文的ModelBuilder 的方法来调用它的Entity 方法。

【问题讨论】:

  • 所以澄清一下,当您执行 DbContext.NewEntityClass.Add(UserCreatedEntity) 之类的操作时,它会失败,因为上下文没有 NewEntityClass 的现有定义?所以你试图通过用户输入在你的 DbContext 中动态创建新的实体类?
  • 没错。我用执行 DbContext.NewEntityClass.Add(UserCreatedEntity) 时遇到的错误更新了问题。
  • 无法从外部访问模型构建器,并且无论如何它不会对上下文实例执行任何操作。一旦您创建了要用于访问此模型的上下文类型,就必须定义您的模型,这是没有办法的。
  • 实体添加后请求一个新的DbContext实例怎么样?有没有办法为范围服务做到这一点?我以这种方式添加上下文:services.AddDbContext<MyDbContext>(),相当于ServiceLifetime.Scoped 生命周期。

标签: c# entity-framework dependency-injection entity-framework-core


【解决方案1】:

您还需要一个新的 DbContext 子类型,因为 OnModelCreating 对于每个 AppDomain 的每个 DbContext 类型仅运行一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多