【问题标题】:Foreign key as primary key in EF Code First?EF Code First中的外键作为主键?
【发布时间】:2015-01-08 08:09:35
【问题描述】:

我需要在我的域中映射 3 个域模型之间的关系,其中一个域模型是关系模型的聚合根。

public class Entity1 {
    public int Id { get; set; }
}

public class Entity2 {
    public int Id { get; set; }
}

public class SuperEntity {
    public int Id { get; set; }
    // bounded context for relationship classes
}

关系实体应如下所示

public class Relationship {
    public int RelationshipId { get; set; }
    public Entity1 Entity1 { get; set; }
    public Entity2 Entity2 { get; set; }
}

接下来,超级实体应该如下所示:

public class SuperEntity {
    public int Id { get; set; }
    public ICollection<Relationship> Relationships { get; set; }
}

现在,映射它的一种可能性是使关系成为一个唯一实体,它有自己的键,并且两个实体都在关系唯一索引内。但是,密钥仅用于“用于关键目的”,没有任何有意义的价值。理想的是这样的关系表:

Table_Relationships
                  [  SuperEntity_Id // Foreign-key to SuperEntity
  PrimaryKey      [  Entity1_Id // Foreign-key to Entity1
                  [  Entity2_Id // Foreign-key to Entity2

意味着 Table_Relationships 的主键是 SuperEntity_Id+Entity1_Id+Entity2_Id。

是否可以在 EF Code First 中进行映射?

【问题讨论】:

    标签: c# sql entity-framework ef-code-first domain-driven-design


    【解决方案1】:

    为什么不使用 DataAnnotations.KeyAttribute (http://msdn.microsoft.com/library/system.componentmodel.dataannotations.keyattribute%28v=vs.110%29.aspx)?在域模型类中定义复杂的主键是一种清晰的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多