[英]Entity Framework model and foreign key property
I have 2 tables that I import to EF model. 我有两个表导入EF模型。
First table has a property [section] that acts as foreign key to the second table. 第一个表有一个属性[section],它充当第二个表的外键。 When I map this property in model to the table and try to compile I get this error: 当我将模型中的此属性映射到表并尝试编译时,我收到此错误:
Problem in Mapping Fragments starting at lines 158, 174: Non-Primary-Key column(s) [Section] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified. 从第158,174行开始映射片段中的问题:非主键列[部分]在两个片段中映射到不同的概念侧属性 - 数据不一致是可能的,因为可以独立地修改相应的概念侧属性。
If i remove this property from the model it passes, but when I query the data I don't have the section field. 如果我从它传递的模型中删除此属性,但当我查询数据时,我没有section字段。
I know that I can get it by using the navigation field and reading this property from the second table, but to make it work I must include the other table in my query. 我知道我可以通过使用导航字段并从第二个表中读取此属性来获取它,但为了使其工作,我必须在查询中包含另一个表。
var res = from name in Context.Table1.Include("Table2")...
Why do I need to include the association just for one field? 为什么我只需要为一个字段包含关联?
UPDATE UPDATE
To make it more clear: 为了更清楚:
Table 1 has fields: 表1包含字段:
ItemId - key ItemId - 键
section - foreign key 部分 - 外键
title 标题
Table 2 has fields: 表2包含字段:
SectionId - key SectionId - 键
Name 名称
When I set the associations the section property from the first table must be removed. 设置关联时,必须删除第一个表中的section属性。
What are your Primary Keys and is one Store Generated? 您的主键是什么,是一个存储生成的? I suspect you are missing a PK or an Identity somewhere. 我怀疑你在某个地方错过了PK或身份。
Tip: One alternative when having mapping problems is to create the model you want in the EDMX designer and then ask it to create the database for you. 提示:出现映射问题时,另一种方法是在EDMX设计器中创建所需的模型,然后让它为您创建数据库。 Compare what it creates to what you have made in SQL and it's often easy to spot the mistakes. 将它创建的内容与您在SQL中创建的内容进行比较,通常很容易发现错误。
In EF 4 you can use FK associations for this. 在EF 4中,您可以使用FK关联 。
In EF 1 the easiest way to get one field from a related table is to project: 在EF 1中,从相关表中获取一个字段的最简单方法是项目:
var q = from t1 in Context.Table1
where //...
select new
{
T1 = t1,
Section = t1.Section.SectionId
};
var section = q.First().Section;
If it's a key property, you can get the value via the EntityKey
: 如果它是一个关键属性,您可以通过EntityKey
获取值:
var t1 = GetT1();
var section = (int)t1.SectionReference.EntityKey.Values[0].Value;
Generally, I don't like this last method. 一般来说,我不喜欢这最后一种方法。 It's too EF-specific, and fails if your query MergeOption
is set to NoTracking
. 它太特定于EF,如果您的查询MergeOption
设置为NoTracking
, NoTracking
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.