EF 4.1映射问题 [英] EF 4.1 Mapping Problem
问题描述
我有一个与自己有关系的课程:
I have a class that have a relationship with itself:
public class Person
{
public long ID { get; set; }
public string Name { get; set; }
public virtual Person Mother { get; set; }
public virtual Person Father { get; set; }
}
当EF 4.1试图映射这个类时,我得到了错误:
'无法确定类型Model.Person和Model.person之间关联的主体结束。必须使用流畅的API或数据注释来明确配置此关联的主要结尾。
When EF 4.1 is trying to map this class I'm getting the follow error: 'Unable to determine the principal end of an association between the types 'Model.Person' and 'Model.person'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.'
我已经尝试了主题的解决方案 EF 4.1 - 模型关系,没有成功。
I already tried the solution of the topic EF 4.1 - Model Relationships without success.
如何我可以解决这个问题吗?
How I can fix that?
谢谢!
推荐答案
一对多的关系(一个人必须有一个父亲和一个母亲,但可以有很多儿子和女儿)我会像这样模型:
Because it's naturally a one-to-many relationship (a person must have one father and one mother but can have many sons and daughters) I'd model it like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasRequired(p => p.Father)
.WithMany();
modelBuilder.Entity<Person>()
.HasRequired(p => p.Mother)
.WithMany();
}
这将在数据库表中创建两个必需的外键,名称为 Mother_ID
和 Father_ID
按惯例。
This will create two required foreign keys in the database table with name Mother_ID
and Father_ID
by convention.
strong>
Edit
如果您想要创建没有母亲和父亲的人,您可以使用可选而不是必需的关系:
If you want to be able to create persons without Mother and Father you can make the relation optional instead of required:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(p => p.Father)
.WithMany();
modelBuilder.Entity<Person>()
.HasOptional(p => p.Mother)
.WithMany();
}
然后数据库表中的外键为空。
Then the foreign keys in the database table are nullable.
如果您不喜欢外键的默认列名称( Mother_ID
和 Father_ID
)可以自定义映射中的列名:
If you don't like the default column names for your foreign keys (Mother_ID
and Father_ID
) you can customize the column names in your mapping:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(p => p.Father)
.WithMany()
.Map(m => m.MapKey("FatherID"));
modelBuilder.Entity<Person>()
.HasOptional(p => p.Mother)
.WithMany()
.Map(m => m.MapKey("MotherID"));
}
这篇关于EF 4.1映射问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!