实体框架核心OnModelCreating(ModelBuilder modelBuilder)

时间:2018-05-14 09:44:36

标签: entity-framework-core

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

实施例 假设我有以下实体

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

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

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

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

protected override void OnModelCreating(ModelBuilder modelBuilder)
{


}

我尝试过很少的东西,例如尝试检索ClrType。但这似乎不起作用。

1 个答案:

答案 0 :(得分:0)

您可以迭代程序集并获取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));
相关问题