gpt4 book ai didi

c# - Entity Framework Code First 复合键上的一对一关系

转载 作者:行者123 更新时间:2023-11-30 14:13:53 27 4
gpt4 key购买 nike

基本上我想要实现的是我有三个表,其中一个父表将始终有一个条目,并且只会填充其他两个表中的一个。我要处理的复杂性是表的主键是两个字段的组合

ParentTable
-----------
UniqueID
OwnerID
[Some more fields]


ChildTable1
-----------
UniqueID
OwnerID
[Some more fields]


ChildTable2
-----------
UniqueID
OwnerID
[Some more fields]

我想知道是否有人对如何通过 EF Code First 最好使用 Fluent API 最好地做到这一点有任何建议。

最佳答案

你只需要定义主键是复合的...

modelBuilder.Entity<Parent>().HasKey(p => new { p.UniqueID, p.OwnerID });
modelBuilder.Entity<Child1>().HasKey(c => new { c.UniqueID, c.OwnerID });
modelBuilder.Entity<Child2>().HasKey(c => new { c.UniqueID, c.OwnerID });

...然后定义两个一对一关系:

modelBuilder.Entity<Parent>()
.HasOptional(p => p.Child1)
.WithRequired(); // or .WithRequired(c => c.Parent)

modelBuilder.Entity<Parent>()
.HasOptional(p => p.Child2)
.WithRequired(); // or .WithRequired(c => c.Parent)

虽然你不能定义一个约束(除非可能通过在数据库中定义一个触发器)来确保给定的 parent 只能引用两个 child 之一,而不是两者。您必须在应用程序的业务逻辑中处理此限制。

关于c# - Entity Framework Code First 复合键上的一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13249438/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com