繁体   English   中英

实体框架代码复合密钥的第一对一关系

[英]Entity Framework Code First One to One relationship on composite key

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

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)

您不能定义约束(除非可能通过在数据库中定义触发器),这将确保给定父级只能引用两个子级中的一个,而不能同时引用两个子级。 您必须在应用程序的业务逻辑中处理此限制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM