【问题标题】:Entity Framework Code First One to One relationship on composite key实体框架代码第一个复合键上的一对一关系
【发布时间】:2012-10-26 07:29:02
【问题描述】:

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

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


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


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

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

【问题讨论】:

    标签: c# .net entity-framework-4 composite-key


    【解决方案1】:

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

    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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多