【发布时间】: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)
);
对于我的类映射,我一直在使用数据注释。没有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 是两个键的一部分,并且由于两个键是复合的,我不能将它应用于导航属性。
如何映射两个具有共同属性的复合外键?还是不能使用数据注释?
【问题讨论】:
标签: c# .net orm entity-framework-6