繁体   English   中英

Net Core:查找 Entity Framework Core 的主键和反射

[英]Net Core: Find Primary Key of Entity Framework Core and Reflection

如何使用 Reflection .dll 从 Entity Framework Core 2 Database Scaffold 中找到主键?

我们需要找到给定 EntityName 的主键成员,并将主键成员作为字符串返回。 对 Sql Server 数据库进行反向脚手架。

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

尝试解决方案:

尝试编写下一行代码,给定字符串实体名称:“产品”。

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"))

其他资源:

更喜欢用反射来做这个,而不是实例化上下文,因为这是代码生成工具,将执行 10 个数据库项目。

使用实体框架的 C# 中的通用存储库

扩展来自评论的建议,您可以在代码中实例化上下文并调用所有 EF 模型检查 API,如Ivan 的回答中所述,如下所示:

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忘记思想实验,这显然令人困惑。 上面的方法不需要你引用你的其他项目,并且不需要除了字符串名称(你看起来有)之外的类型的先验知识。 当您实例化您的 db 上下文时,EF 中的基类构造函数将处理您所有的自定义覆盖,并将返回一个完全构建的模型(即所有属性都将被考虑在内)。 同样,只要您只使用 EF 元数据 API(可在基本DBContext类上使用),就不需要引用。 希望这能澄清。

UPD2 :在评论中跟进我的IL Emit想法。 我的博客中查看实现和更多背景信息。 这使我能够消除异常(尽管仍然必须至少有一个可用的数据库提供程序)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM