c# - 如何使用 Entity Framework 6 将单个属性映射为多个复合外键的一部分?

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

我正在设置到遗留数据库的 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 是两个键的一部分,并且由于这两个键都是复合键,所以我无法将其应用于导航属性。

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

最佳答案

您可以使用带有属性名称的逗号分隔字符串在导航属性上应用 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 :

If you add the ForeigKey attribute to a foreign key property, you should specify the name of the associated navigation property. If you add the ForeigKey attribute to a navigation property, you should specify the name of the associated foreign key(s). If a navigation property has multiple foreign keys, use comma to separate the list of foreign key names.

关于c# - 如何使用 Entity Framework 6 将单个属性映射为多个复合外键的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903206/

相关文章:

python - SQLAlchemy 单表继承的一对多关系 - 声明式

c# - 如何向 OpsGenie 发出 POST 请求?

c# - 枚举 COM/DCOM/COM+ IN_PROC 实例

c# - 使用 System.Reactive 订阅/监听流的 "side events"

c# - 在使用特定子类型调用时查找特定方法的用法

c# - 如何在 C# .net core/.net standard 中获取可用内存或使用内存

c# - 获取字符串中某个索引后第一个检测到的空间的索引

python - 当相关列不存在时 SQLAlchemy 忽略过滤器

java - JPA @SqlResultSetMapping 无法处理要映射到空 POJO 的空 sql 结果 - 而是抛出异常

c# - 当只有显式更改的行应该被更改时,datagrid 中的多行正在更改