EntityFramework'加入'在复合键

时间:2016-12-06 10:47:29

标签: c# entity-framework

目前适用于EF5,但计划很快升级到EF6。

使用以下表格: 注意这些表是简化来解释问题的,真正的表显然更复杂。数据库是遗留数据库,我无法更改表。 BarRed和BarBlue是不同的表,具有不同的结构,只有它们链接到Foo的方式是相同的。

[Table("Foo")]
public class Foo
{
    // Id+ColorCode is the primary Key on this table
    [Key,Column(Order=0)]
    int Id;
    [Key,Column(Order=1)]
    int ColorCode;  // 1=red, 2=blue, 3=green, …

    public virtual ICollection<BarRed> BarRed { get; set; } // when ColorCode==1, empty/null otherwise
    public virtual ICollection<BarRed> BarBlue { get; set; } // when ColorCode==2, empty/null otherwise
}

[Table("BarRed")]
public class BarRed
{
    [Key]
    int Id; // Id is the primary key in this table.
    // There is no ColorCode column in this table, essentially the ColorCode for each record in this table is the literal value 1.

    [ForeignKey("Id,1")]    // This doesn't work, doesn't accept the 1
    public virtual Foo Foo { get; set; }
}

[Table("BarBlue")]
public class BarBlue
{
    [Key]
    int Id; // Id is the primary key in this table.
    // There is no ColorCode column in this table, essentially the ColorCode for each record in this table is the literal value 2.

    [ForeignKey("Id,2")]    // This doesn't work, doesn't accept the 2
    public virtual Foo Foo { get; set; }
}

因此,简而言之,当“多对多”关系中,如何让EntityFramework以一对多关系链接2个表。边表不具有其中一个关键段的显式列,但应在所有行上使用固定的文字值。

我也有一个类似的问题/问题在另一个方向,一对多,其中一个&#39;一个&#39;对于每条记录,没有明确的列,但应使用文字值。

我可以从SQL加入表,这确实可以正常使用索引,我需要这个以便EF从OData访问数据库。

0 个答案:

没有答案