网络核心:查找实体框架核心的主键和反射

时间:2019-12-30 10:29:53

标签: c# .net entity-framework .net-core entity-framework-core

如何使用Reflection .dll从Entity Framework Core 2数据库支架中找到主键?

我们需要找到给定EntityName的主键成员,并以字符串形式返回主键成员。 在Sql Server数据库上进行反向脚手架。

modelBuilder.Entity<Product>(entity =>
{
    entity.HasKey(e => e.ProductInfoId)
     .HasName("PK_ProductInfoId");

尝试解决方案:

在给定字符串Entity Name:“ Product”的情况下尝试编写下一行代码。

var assembly = Assembly.LoadFrom(@"C:\OnlineShoppingStore\bin\Debug\netcoreapp2.2\OnlineShoppingStore.dll");

assembly.GetTypes().Where(d=>d.Name = "OnlineStoreDbContext")

etc GetProperties().Where(e=>e.Name == "Product"))

其他资源:

宁愿使用Reflection来执行此操作,而不是实例化上下文,因为这是针对代码生成工具的,它将针对10个db项目进行操作。

Generic Repository in C# Using Entity Framework

1 个答案:

答案 0 :(得分:0)

根据注释中的建议进行扩展,您可以在代码中实例化上下文并按Ivan's answer所述调用所有EF模型检查API,如下所示:

var assembly = Assembly.LoadFrom(@"C:\OnlineShoppingStore\bin\Debug\netcoreapp2.2\OnlineShoppingStore.dll");
var contextType = assembly.GetTypes().First(d => d.Name == "OnlineStoreDbContext");
var ctx = Activator.CreateInstance(contextType) as DbContext; // instantiate your context. this will effectively build your model, so you must have all required EF references in your project
var p = ctx.Model.FindEntityType(assembly.GetTypes().First(d => d.Name == "Product")); // get the type from loaded assembly
//var p = ctx.Model.FindEntityType("OnlineStoreDbContext.Product"); // querying model by type name also works, but you'd need to correctly qualify your type names
var pk = p.FindPrimaryKey().Properties.First().Name; // your PK property name as built by EF model

UPD 忘记思想实验,这显然很令人困惑。 上面的方法不需要您引用其他项目,除了字符串名称(看起来很像)之外,不需要其他类型的先验知识。 当您实例化数据库上下文时,EF中的基类构造函数将处理所有自定义覆盖,并将返回完整的模型(即,将考虑所有属性)。同样,只要您仅使用EF元数据API(在基础DBContext类中可用),就不需要引用。希望这可以澄清。