[英]Entity Framework Code First One to One relationship on composite key
Basically what I am trying to achieve is I have three tables, one parent will always have an entry in it and only one of the other two tables will be populated. 基本上我想要实现的是我有三个表,一个父表将始终有一个表,并且只会填充其他两个表中的一个。 The complexity that I am dealing with is that the primary key for the tables is the combination of two fields 我正在处理的复杂性是表的主键是两个字段的组合
ParentTable
-----------
UniqueID
OwnerID
[Some more fields]
ChildTable1
-----------
UniqueID
OwnerID
[Some more fields]
ChildTable2
-----------
UniqueID
OwnerID
[Some more fields]
I was wondering if anyone has any suggestions on how best to do this through EF Code First preferably using the Fluent API. 我想知道是否有人建议如何通过EF Code First最好地使用Fluent API。
You just need to define that the primary keys are composite... 您只需要定义主键是复合的......
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 });
...and then define the two one-to-one relationships: ...然后定义两个一对一的关系:
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)
You cannot define a constraint though (except probably by defining a trigger in the database) that would ensure that a given parent may only refer to one of the two children, but not to both. 您不能定义约束(除非可能通过在数据库中定义触发器),这将确保给定父级只能引用两个子级中的一个,而不能同时引用两个子级。 You must handle this restriction in your application's business logic. 您必须在应用程序的业务逻辑中处理此限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.