实体框架中的显式vs隐式外键列

时间:2015-02-17 20:11:13

标签: c# entity-framework

偶尔,我遇到了Entity Framework生成的迁移问题。

通常,我有这样的模型:

public class Account{
    int ID { get; set;}
    public virtual List<AccountInfo> AccountInfo { get; set;}
}

public class AccountInfo{
    int ID {get; set;}
    //Other fields
    [ForeignKey("Account")]
    public int AccountID { get; set;}
    public virtual Account Account { get; set;}
}

通常,这样可以正常工作并按预期生成模型。其他时候(通常在修改现有实体时 - 我不确定在创建新实体时我是否曾经看到过这种情况),Entity Framework将尝试为我生成外键列。使用前面的示例,它会尝试生成以下内容:

AccountInfo
     ID int
     Account_ID int
     AccountID int //Sometimes doesn't even do this

Account
     ID int

然后在Account_ID上定义外键。

据我所知,如果您没有定义显式外键,Entity Framework将尝试为您生成一个(由于导航属性,您的模型可能不需要拥有外键)。但是,由于我明确配置了外键,我希望它能够顺从我的配置。

通常我只是手动编辑迁移,以便在正确的属性上设置外键关系,但我认为这不是我应该做的。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

经过一些反复试验,我发现了问题。

我正在使用的实体基于生成的代码,部分类用于我需要扩展它们的位置。我正在扩展它们以便它们符合特定的界面。

我已经根据生成的代码创建了Account和AccountInfo表,但添加了正确的外键关系。为了使它们符合适当的界面,我做了以下几点:

//Generated code
public partial class Account{
    public List<AccountInfo> GeneratedAccountInfos { get; set; }
    //other fields
}
//My code
public partial class Account : SomeAccountInterface{
    public int ID {get; set;}
    //Correct name to implement AccountInfos property of SomeAccountInterface
    public virtual List<AccountInfo> AccountInfos {get; set;} 
    List<SomeAccountInfoInterface> SomeAccountInterface.AccountInfos{
         get{ return AccountInfos; }
    }
}
public partial class AccountInfo{
     //some generated fiels
}
public partial class AccountInfo : SomeAccountInfoInterface{
    public virtual Account {get; set;}
    [ForeignKey("Account")]
    public int AccountID {get; set;}
}

List&lt; AccountInfo&gt;类型的两个属性困惑的EntityFramework也让问题变得非常明显(我也遇到了#34; Sequence包含多个匹配元素&#34;在创建迁移期间,它指向了正确的方向)。删除AccountInfos属性,同时保留显式接口定义(改为参考GeneratedAccountInfos),修复了该问题。