.net EF代码中的一对一映射问题
考虑以下情况:.net EF代码中的一对一映射问题,.net,entity-framework,.net,Entity Framework,考虑以下情况: public class House { public string Name { get; set; } public virtual Person Person1 { get; set; } public virtual Person Person2 { get; set; } } public class Person { public string FirstName { get; set; } public string Las
public class House
{
public string Name { get; set; }
public virtual Person Person1 { get; set; }
public virtual Person Person2 { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public House House { get; set; }
}
// Relationships
this.HasOptional(t => t.Person1)
.WithRequired(t => t.House);
this.HasOptional(t => t.Person2)
.WithRequired(t => t.House);
当我尝试插入House的实例时,会引发MetaDataException:
指定的架构无效。错误:(36,6):错误0040:类型
名称空间Company.Models(别名=Self)中未定义House_Person1
经过更多的黑客攻击后,我认为这是可行的:
// Relationships
this.HasOptional(t => t.Person1)
.WithRequired();
this.HasOptional(t => t.Person2)
.WithRequired();
但我不会让那个人,EF居住的房产。我可以模仿这种行为吗(如下所示)
您不能在两种不同的关系(
House\u Person1
和House\u Person2
)中使用相同的导航属性(Person.House
)
另外一个限制是EF只支持真正的一对一关系。这意味着相关的房屋
和人员
必须具有相同的主键值。但是从那以后,House.Person1
和House.Person2
需要与House
具有相同的PK值。换句话说:Person1
和Person2
永远不能是不同的人
我建议您将您的关系映射为一对多关系,并在应用程序的业务逻辑中确保一个机构
不能有两个以上的人
。(因为您当前的映射允许Person1
和Person2
是可选的,所以将允许零人或只允许一人):
您可以像在上一个代码片段中一样,在Person
中使用House
属性,但需要将其从模型中排除:
modelBuilder.Entity<Person>()
.Ignore(t => t.House);
modelBuilder.Entity()
.忽略(t=>t.House);
Person.House
不再是导航属性,当您从数据库加载Person
实体时,您无法加载它(通过快速加载或延迟加载)。我确实希望保留Person1和Person2。你还能想到别的吗?我在考虑没有导航属性Person.House。请参阅已编辑的问题。@Trainee4Life:请参阅我的编辑。如上所述,使用一对一映射来映射两个个人
属性没有意义,因为它们将与房屋
共享主键,因此两个个人
不能不同。
public class House
{
public string Name { get; set; }
public virtual ICollection<Person> People { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public House House { get; set; }
}
this.HasMany(t => t.People)
.WithRequired(t => t.House);
this.HasOptional(t => t.Person1)
.WithMany();
this.HasOptional(t => t.Person2)
.WithMany();
modelBuilder.Entity<Person>()
.Ignore(t => t.House);