我有这门课
public class Parent
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual Child Child { get; set; }
}
和一个子类
public class Child
{
[Key]
[ForeignKey]
public int ParentId { get; set; }
public string Name { get; set; }
public virtual Parent Parent { get; set; }
}
这种关系使得 parent 可以有 0 个或 1 个 child 。我检查过 SO 并找到了两个解决方案。
modelBuilder.Configurations.Add(new ParentChildMap());
// solution 1
class ParentChildMap : EntityTypeConfiguration<Child>
{
public ParentChildMap()
{
HasRequired(t => t.Parent).
WithRequiredDependent(t => t.Child);
}
}
// solution 2
class ParentChildMap : EntityTypeConfiguration<Child>
{
public ParentChildMap()
{
HasOptional(c => c.Parent)
.WithRequired(c => c.Child);
}
}
事实是,它们都在工作!但问题是,我不确定哪个是正确的。哪个为我提供了一位 parent 只能有 0 或 1 个 child 的映射。然后,另一个人在说什么?
最佳答案
让我们将相关实体及其基数添加到所需的关系中:
父 1 <--> 0..1 子
你可以这样读:
(1) --> 0..1 Child 表示每个Parent可以有0个或1个Child,或者换句话说,Child
Parent
的属性(property)实体是可选的
(2) Parent 1 <-- 表示每个 Child 总是有 1 个 Parent,或者换句话说,Parent
Child
的属性(property)实体是必需的。
对应上面来自Child
的fluent配置边是:
HasRequired(c => c.Parent).WithOptional(p => p.Child);
或者来自 Parent
边:
HasOptional(p => p.Child).WithRequired(c => c.Parent);
这两个是正确的并且完全等效 - 您可以使用一个或另一个取决于您是否从 Child
开始配置(如您的样本)或来自 Parent
.为避免出现差异,切勿同时执行这两项操作。
为什么您当前的两个解决方案都不正确?
因为:
(解决方案 1)
HasRequired(t => t.Parent).WithRequiredDependent(t => t.Child);
代表Parent 1 <--> 1 Child关系(parent必须总是有1个child)。
(解决方案 2)
HasOptional(c => c.Parent).WithRequired(c => c.Child);
代表Parent 0..1 <--> 1 Child关系( child 可以有0个或1个 parent , parent 必须总是有1个 child ),即与你想要的相反。 p>
关于c# - Entity Framework 1对0或1关系配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49305921/