Entity Framework 0..1 to 0 relation(实体框架 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 一起应用?
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 可以包含 First 的一个实例(取决于某种使用属性).First 不包含 Second 的任何实例.
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; }
}
原因是为了在数据库中强制一对一关系,外键在 Second
实体中必须是唯一的.但实体框架不支持唯一键 - 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 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架 0..1 到 0 关系
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01