EF Code First外键关联属性

时间:2015-10-30 16:22:56

标签: c# entity-framework data-annotations code-first

好的,我想知道是否有办法将外键关系映射到EF Code First Data Annotations,而不是在名称不匹配时使用Fluent API。这是我的情景。 我有两个与外键有一对多关系的表。

安全表:   int SecurityID(PK)   //其他列   int IncomeFrequencyID(FK)

频率表   int FrequencyID(PK)   //其他列

所以IncomeFrequencyID映射到FrequencyID

然后在我的Code First中:

public class Security
{
    public int SecurityID {get;set;}
    //Other properties
    public int IncomeFrequencyID {get;set;}

    //Navigation Properties
    public virtual Frequency IncomeFrequency {get;set;}
}

public class Frequency
{
    public int FreqencyID {get;set;}
    //Other properties
}

有没有办法使用数据注释完成EF关系? 也许使用AssociationAttribute

[Association("FK_Security_Frequency", "IncomeFrequencyID", "FrequencyID", IsForeignKey = true)]

1 个答案:

答案 0 :(得分:2)

使用ForeignKey属性,例如:

public class Security
{
    public int SecurityID {get;set;}
    //Other properties
    public int IncomeFrequencyID {get;set;}

    //Navigation Properties
    [ForeignKey("IncomeFrequencyID")]
    public virtual Frequency IncomeFrequency {get;set;}
}

另一方面,将其标记为主键:

public class Frequency
{
    [Key]
    public int FreqencyID {get;set;}
    //Other properties
}