实体框架0..1到0的关系
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 ... ???
}
}
Second 可能会引用 First。但 First 从未引用 Second。是否可以将此映射应用于 Entity Framework 4.1?
编辑: 以前,这是我的解决方案:
this.HasOptional(s => s.First)
.WithOptionalDependent()
.WillCascadeOnDelete(false);
Second 可以包含 First 的一个实例(取决于某种用途属性)。 First 不包含 Second 的任何实例。
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 ... ???
}
}
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?
EDIT:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当外键也是依赖实体的主键时,一对一关系才可能。因此,正确的映射是:
原因是为了在数据库中强制执行一对一关系,外键在
Second
实体中必须是唯一的。但实体框架不支持唯一键 - EF 的唯一唯一值是主键。这是EF的局限性。Morteza Manavi 的博客。解决方法基于将关联映射为一对多,并通过在自定义数据库初始值设定项中引入唯一约束来强制数据库中的唯一性。
One-to-one relation is possible only if foreign key is also primary key of dependent entity. So the correct mapping is:
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.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.
如果您尝试实现一对一关系,则最多只有一个
Second
实体与First
实体关联,并且没有相反,您可以尝试以下操作:不过,您可以使用单独的
First_id
列来执行此类关联,但这样您将有效地创建 1 对 N 关系。它可以通过 UNIQUE 约束“强制”为 1 对 1,但由于 EF 的限制,您将无法创建反向属性(正如 Ladislav 提到的):If you're trying to achieve a 1-to-1 relationship, where there is at the most only one
Second
entity associated to aFirst
entity, and where there is no reverse property try the following:You can however use a separate
First_id
column to do this kind of association, but then you would be effectively creating a 1-to-N relationship. It can be 'forced' to be 1-to-1 via a UNIQUE constraint, but you won't be able to create a reverse property due to a limitation in EF (as Ladislav mentioned):