我正在设置到遗留数据库的 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)
);
对于我的类映射,我一直在使用数据注释。没有 AllowMultiple
的 ForeignKeyAttribute
是 AttributeUsage
,因此一个属性只能有一个 [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/