如何使用模型优先方法在 EF4 中创建 1x0..1 关联?
考虑以下示例模型:
- Person has 0..1 User
- User has 1 Person
Attempt 1:
- 我从
Person 中拖动了一个关联
到模型设计器上的User
。 - 我修复了基数以满足我的需求(默认为 1xN)
- 我从模型生成了 DDL
问题:
- 输出
User
表有一个Person_id
没有唯一约束的列。也就是说,它不是 1x1 关系,因为许多用户可以引用同一个人。这里一定有问题
尝试2:
- 在模型设计器上将关联从“Person”拖到“User”。
- 修复了基数以满足我的需求(默认为 1xN)
- 选择关联并单击属性窗口上的
Referential Constraint
按钮来编辑关联 - Selected Person to be the Primary and User to be Dependent type
- 选择
Principal Key
作为Id,Dependent Property
也作为Id(我在某处读过,我应该对这两种类型使用相同的密钥)
问题:
我运行此代码:
using (var context = new Locadora())
{
User user = new User ();
user.PasswordHash = "hash";
user.Pessoa = new Person();
user.Pessoa.Nome = "André";
context.Usuários.AddObject(user);
context.SaveChanges();
}
- SaveChanges 触发此异常:
ReferentialConstraint 中的依赖属性映射到存储生成的列。列:“ID”
所以我现在别无选择。我不知道如何在实体框架中实现 1x1 和 1x0..1 关系。
我该怎么做?
Consider the following example model:
- Person has 0..1 User
- User has 1 Person
Attempt 1:
- I dragged an association from
Person
toUser
on the model designer. - I fixed the cardinality to meet my needs (the default is 1xN)
- I generated the DDL from model
Problem:
- The output
User
table has aPerson_id
column with no unique constraint. That is, it's not a 1x1 relationship as many Users can reference the same Person. There must be something wrong here
Attempt 2:
- Dragged an association from Person to User on the model designer.
- Fixed the cardinality to meet my needs (the default is 1xN)
- Selected the association and clicked the
Referential Constraint
button on the properties window to edit the association - Selected Person to be the Principal and User to be the Dependent type
- Chosen the
Principal Key
to be Id and theDependent Property
to be also Id (I've read somewhere that I should use the same key for both types)
Problem:
I run this code:
using (var context = new Locadora())
{
User user = new User ();
user.PasswordHash = "hash";
user.Pessoa = new Person();
user.Pessoa.Nome = "André";
context.Usuários.AddObject(user);
context.SaveChanges();
}
- SaveChanges triggers this exception:
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'
So I am out of choices now. I don't know how to implement a 1x1 neither a 1x0..1 relationship in Entity Framework.
How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一次尝试无法成功,因为当前的 EF 版本根本不支持唯一键。第二种方法不起作用,因为您的依赖实体无法自动生成密钥 =
StoreGeneratePattern
必须设置为None
。The first attempt can't work because current EF version doesn't support Unique keys at all. Second approach doesn't work because you dependent entity can't have autogenerated key =
StoreGeneratedPattern
must be set toNone
.