【问题标题】:Entity framework core OnModelCreating(ModelBuilder modelBuilder)实体框架核心 OnModelCreating(ModelBuilder modelBuilder)
【发布时间】:2018-05-14 19:56:51
【问题描述】:

我想检索实现特定接口的实体的Type。我想在 OnModelCreating 方法中检索它。

示例 假设我有以下实体

public class Product : IProductBase {
   public int ProductId {get;set;}
}

我还有一个实体没有实现IProductBase,例如:

Public class ProductInventory {
  public int Id {get;set;}
}

在下面的 onModelCreating 中,我希望能够检索所有已实现 IProductBase 接口的实体的 Type(s)

protected override void OnModelCreating(ModelBuilder modelBuilder)
{


}

我尝试了一些方法,例如尝试检索 ClrType。但这似乎不起作用。

【问题讨论】:

  • 试试var type = typeof(IProductBase ); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p));包含命名空间using System; using System.Linq;
  • 还有 1 个问题 OnModelCreating 只调用一次对吗?
  • 每个唯一提供商类型一次。如果您的目标是单一数据库类型(例如 SqlServer),那么它将被调用一次。此外,不是迭代所有程序集中的所有类型,而是仅迭代modelBuilder.Mode.GetEntityTypes(),如此处所示stackoverflow.com/questions/45096799/…
  • @John 当你做 Update-Database 意味着当你尝试应用迁移时它会被调用。如果您需要帮助,请告诉我
  • @IvanStoev modelBuilder.Mode.GetEntityTypes() 返回 IMutableEntityType 而不是我需要反射的 system.type

标签: entity-framework-core


【解决方案1】:

您可以迭代程序集并获取IProductBase 类型的所有实体。

using System;
using System.Linq;

var type = typeof(IProductBase ); 
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));

正如@Ivan Stoev 所建议的那样。您还可以使用以下方法获取所有实体。感谢@Ivan 提出的宝贵建议。

var type = modelBuilder.Model.GetEntityTypes(typeof(FullAuditedEntity));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 2020-07-01
    • 2021-07-14
    • 1970-01-01
    相关资源
    最近更新 更多