实体框架0..1 0的关系 [英] Entity Framework 0..1 to 0 relation
问题描述
class First
{
[Key]
public int Id { get; set; }
}
class Second
{
[Key]
public int Id { get; set; }
public int? First_Id { get; set; }
[ForeignKey("First_Id")]
public First First { get; set; }
}
public class SecondMapping : EntityTypeConfiguration<Second>
{
public SecondMapping ()
: base()
{
this.HasOptional(s => s.First)
.With ... ???
}
}
其次可能要首先参考。但首先从来没有第二的参考。是否有可能与实体框架4.1
Second may have a reference to First. But First never has a reference to Second. Is it possible to apply this mapping with Entity Framework 4.1?
修改应用此映射:
以前,这是我的解决方案:
Previously, that was my solution:
this.HasOptional(s => s.First)
.WithOptionalDependent()
.WillCascadeOnDelete(false);
二可以包含首先的一个实例(依赖于某种用途属性的)。第一不包含第二的任何实例
Second could contain one instance of First (dependent on some kind of Usage-Attribute). First doesn't contain any instance of Second.
推荐答案
一对一的关系是可能的,只有外键都是主相关实体的关键。所以,正确的映射是:
One-to-one relation is possible only if foreign key is also primary key of dependent entity. So the correct mapping is:
class First
{
[Key]
public int Id { get; set; }
}
class Second
{
[Key, ForeignKey("First")]
public int Id { get; set; }
public First First { get; set; }
}
的原因是,执行数据库中的一个对一关系外键必须在二
实体独一无二的。但是,实体框架不支持唯一的密钥 - 为EF唯一的独特价值是主键。这是EF的限制。
The reason is that to enforce one-to-one relation in the database foreign key must be unique in the Second
entity. But entity framework doesn't support unique keys - the only unique value for EF is primary key. This is limitation of EF.
有上的Morteza Manavi的博客。解决方法是基于映射的关联为一个一对多并通过引入自定义数据库初始化唯一约束强制执行数据库的唯一性。
There is workaround described on Morteza Manavi's blog. Workaround is based on mapping association as one-to-many and enforcing uniqueness in database by introducing unique constraints in custom database initializer.
这篇关于实体框架0..1 0的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!