在 Entity Framework 4.1 Code First 中创建双向一对一关系
我想使用 EF Code First 在两个实体之间创建双向一对一关系。我在使用以下代码时遇到问题。你认为我应该做什么?
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public int ProfileID { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int UserID { get; set; }
public User User { get; set; }
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
}
我想在两个实体中都拥有导航属性和外键。
这给了我错误。我可以在 Fluent Mapping API 中做什么来完成这项工作?
I want to created Bi-Directional One-One relationship between two entities using EF Code First. I have trouble with the following code. What do you think I should do?
public class User
{
public string ID { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public int ProfileID { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int UserID { get; set; }
public User User { get; set; }
public int ProfileID { get; set; }
public string ProfileName { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastUpdateDate { get; set; }
}
I want to have both Navigation property and Foreign Key in both the entities.
This gives me error. What can do I in Fluent Mapping API to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用这个:
这是在 EF 中建立一对一关系的唯一有效方法 - 依赖实体的 PK 也必须是主体实体的 FK。 EF 中不存在双向一对一关系,因为它无法在 EF 中工作。
人们有时克服这个问题的方法是两个一对多关系,其中主体没有依赖实体的导航集合+数据库中手动定义的唯一键。这需要手动映射:
并且在映射中您将定义:
现在您必须在数据库中定义唯一键 - 如果您使用代码首先使用 自定义数据库初始化r。请注意,双向一对一仍然是错误的概念,因为双方都需要唯一的 FK,其中 NULL 仍然包含在唯一值中,因此一旦在
Profile
之前插入User
,就必须不能是没有个人资料
的任何其他用户
。这可能会导致可序列化事务。Use this:
That is the only valid way to build one-to-one relation in EF - PK of the dependent entity must be also FK to principal entity. There is nothing like bidirectional one-to-one relation in EF because it cannot work in EF.
The way how people sometimes overcome this are two one-to-many relations where principal doesn't have navigation collection for dependent entities + manually defined unique keys in the database. That require manual mapping:
And in mapping you will define:
Now you must define Unique keys in the database - if you are using code first use custom database initializer. Be aware that still bidirectional one-to-one is wrong concept because both sides demand unique FK where NULL is still included in unique values so once you insert
User
beforeProfile
there mustn't be any otherUser
withoutProfile
. That probably leads to serializable transaction.