【问题标题】:How can I map a single Property as part of multiple compound Foreign Keys using Entity Framework 6?如何使用 Entity Framework 6 将单个属性映射为多个复合外键的一部分?
【发布时间】:2016-10-06 18:28:02
【问题描述】:

我正在设置一个到旧数据库的 EF Code First 映射。对象模型是数据库架构的一对一(不尝试美化架构)。

该数据库有一个表,其中包含两个复合外键,并且两个外键中都使用了一列。这是一个伪样本:

CREATE TABLE This_One
(
  CommonColumn INT NOT NULL, -- NOTE: This column is part of both Compound FK's
  ColumnOne INT NOT NULL,
  ColumnTwo INT NOT NULL,

  CONSTRAINT FK_ONE FOREIGN KEY (CommonColumn, ColumnOne)
    REFERENCES Other_One (CommonColumn, ColumnOne),
  CONSTRAINT FK_Two FOREIGN KEY (CommonColumn, ColumnTwo)
    REFERENCES Other_Two (CommonColumn, ColumnTwo)
);

对于我的类映射,我一直在使用数据注释。没有AllowMultipleForeignKeyAttributeAttributeUsage,因此一个属性只能应用一个[ForeignKey],并且该属性只接受一个名称。

// Can't apply the compound keys this way
[Table("This_One")]
public class FKOnProperty
{
  public int Common {get;set;}

  [ForeignKey(nameof(OtherOne))] // [ForeignKey(nameof(OtherTwo))]
  public int One {get;set;}

  ...

  public OtherOne OtherOne {get;set;}

  public OtherTwo OtherTwo {get;set;}
}

// Or this way
[Table("This_One")]
public class FKOnNavigation
{
  public int Common {get;set;}

  public int One {get;set;}

  public int Two {get;set;}

  [ForeignKey(nameof(One))] // [ForeignKey(nameof(Two))]
  public OtherOne OtherOne {get;set;}

  ...
}

简而言之,我不能使用属性来指定CommonColumn 是两个键的一部分,并且由于两个键是复合的,我不能将它应用于导航属性。

如何映射两个具有共同属性的复合外键?还是不能使用数据注释?

【问题讨论】:

    标签: c# .net orm entity-framework-6


    【解决方案1】:

    您可以使用带有属性名称的逗号分隔字符串在导航属性上应用ForeignKey 属性:

    public class This_One
    {
        [Key, Column(Order = 1)]
        public int CommonColumn { get; set; }
        [Key, Column(Order = 2)]
        public int ColumnOne { get; set; }
        [Key, Column(Order = 3)]
        public int ColumnTwo { get; set; }
    
        [ForeignKey("CommonColumn,ColumnOne")]
        public Other_One Other_One { get; set; }
        [ForeignKey("CommonColumn,ColumnTwo")]
        public Other_Two Other_Two { get; set; }
    }
    

    摘自ForeignKey构造函数documentation

    如果将 ForeigKey 属性添加到外键属性,则应指定关联导航属性的名称。如果将 ForeigKey 属性添加到导航属性,则应指定关联外键的名称。 如果导航属性有多个外键,请使用逗号分隔外键名称列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2013-11-26
      相关资源
      最近更新 更多