4Manuals

  • PDF Cloud HOME

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

    获取Hough线的交点OpenCV C ++ 如何将字符串“ text1”设置为包含项目text1,text2,test3的组合框的选定项目? 为什么System.Net.Mail.MailAddress构造函数在域部分中解析带有斜杠“ /”的电子邮件? Android 10,API29:在应用程序文件夹中使用C ++库编写文件会使应用程序崩溃 Unity-LineRenderer没有出现在版本(2D)上 按下按钮后,电话中未显示通知 ASP.net,使用WebConfig httpErrors重定向到区域内的控制器不起作用 获取会议室详细信息 我们如何将参数Line转换为Station? ASIO io_service在第二次run()调用时不处理后处理程序

如何使用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类中可用),就不需要引用。希望这可以澄清。



Similar searches
    滚动到对话框末尾后无法拖动项目-react-dnd heroku在每次部署期间都会继续安装django软件包 NAMESPACE ERROR'…不是名称空间名称' 如何使用localStorage恢复页面重新加载时vimeo的暂停时间? 如何在路径中转义百分号(批处理脚本)