How do I create a 1x0..1 association in EF4 using Model-First approach?
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 Us开发者_Go百科ers 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?
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 to None
.
精彩评论