[英]In EF Database First Approach when instantiating a model, it fails to determine the principal end of an association between the types
Basically, I have two tables. 基本上,我有两个表。 Principal table let's say "Foo" that has PK column ID of type int, and dependent table "Bar" that has PK column FooID of type int that is also a FK to ID of "Foo". 假设主表的“ Foo”具有int类型的PK列ID,而从属表“ Bar”具有的int PK列FooID也是int类型,其FK到ID也是“ Foo”。
As I understood, the problem is that dependent type lacks [Foreign Key] attribute on the primary key property. 据我了解,问题在于从属类型在主键属性上缺少[Foreign Key]属性。 Problem can be resolved on dependent type's side by either specifying [Foreign Key] attribute on PK or specifying [Required] attribute on the navigation property of PK. 通过在PK上指定[外键]属性或在PK的导航属性上指定[必需]属性,可以在从属类型方面解决问题。
I have tried to add [Required] but it didn't help much. 我尝试添加[必需],但并没有太大帮助。 Problem was resolved but models couldn't pass validation because of that. 问题已解决,但模型因此无法通过验证。 I don't want them to be validated because those properties can be null sometimes, at least when I use them to insert to DB. 我不希望对它们进行验证,因为有时至少在使用它们插入数据库时,这些属性可能为null。 Turning off validation check on SaveChanges() also didn't help because I started to get other weird exceptions. 关闭SaveChanges()的验证检查也无济于事,因为我开始遇到其他奇怪的异常。
Now I want to try specifying [ForeignKey] attribute but can't figure out how to make it happen. 现在,我想尝试指定[ForeignKey]属性,但不知道如何实现它。 I don't have experience with T4 (*.tt file). 我没有使用T4(*。tt文件)的经验。 I don't know how to check property if it's a fk and don't know how to get its name. 我不知道如何检查属性是否为fk,也不知道如何获得其名称。 So please help me. 所以请帮帮我。
I tried to re-create EDMX and ran some db insertions on a different machine. 我试图重新创建EDMX,并在另一台计算机上运行了一些数据库插入操作。 Strangely, this error does not occur on that machine. 奇怪的是,在该计算机上不会发生此错误。 Found out recently that EF does not need DataAnnotaions because it uses mappings from XML files not from code from here . 最近发现EF不需要DataAnnotaions,因为它使用的是XML文件的映射,而不是此处的代码。 So I guess the problem was that my old pc somehow couldn't correctly create EDMX or couldn't use mappings from xml. 所以我想问题是我的旧电脑无法正确创建EDMX或无法使用xml映射。 The cause is not clear to me yet. 原因尚不清楚。 But the problem was resolved. 但是问题解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.