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

Sat*_*tal 3 .net c# composite-key entity-framework-4

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

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


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


ChildTable2
-----------
UniqueID
OwnerID
[Some more fields]
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人建议如何通过EF Code First最好地使用Fluent API.

Sla*_*uma 7

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

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 });
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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