C# 实体框架中的显式与隐式外键列

C# 实体框架中的显式与隐式外键列,c#,entity-framework,C#,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")] p

偶尔,我会遇到实体框架生成的迁移问题

通常,我有这样一个模型:

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;}
}
然后定义帐户ID上的外键

我理解,如果您不定义显式外键,Entity Framework将尝试为您生成一个外键(因为您的模型可能不需要外键,因为导航属性)。然而,由于我显式地配置了外键,我希望它遵从我的配置


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

经过一番尝试和错误,我发现了问题所在

我正在使用的实体是基于生成的代码的,在我需要扩展它们的地方有分部类。我扩展了它们,使它们符合特定的接口

我已经根据生成的代码创建了Account和AccountInfo表,但添加了正确的外键关系。为了使它们符合正确的接口,我执行了以下操作:

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

Account
     ID int
//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;}
}
//生成的代码
公共部分类帐户{
公共列表生成帐户信息{get;set;}
//其他领域
}
//我的代码
公共部分类帐户:SomeAccountInterface{
公共int ID{get;set;}
//实现SomeAccountInterface的AccountInfos属性的正确名称
公共虚拟列表AccountInfos{get;set;}
列出一些AccountInterface.AccountInfos{
获取{return AccountInfos;}
}
}
公共部分类AccountInfo{
//一些生成的域
}
公共部分类AccountInfo:SomeAccountInfoInterface{
公共虚拟帐户{get;set;}
[外汇钥匙(“账户”)]
public int AccountID{get;set;}
}

带有类型列表的两个属性混淆了EntityFramework,也使问题变得不明显(在迁移创建过程中,我还遇到了“序列包含多个匹配元素”,这为我指明了正确的方向)。删除AccountInfos属性,同时保留显式接口定义(改为引用GeneratedAccountInfo),修复了该问题。

不幸的是,除了“应该可以工作”之外,什么都不能说。我看你这里的代码没有问题。我唯一能推荐的是发布发生这种情况的特定案例的完整代码,也就是说,直接复制并粘贴所有您拥有的内容-不要只是试图为我们将其简化。也许到那时,有人能发现一些东西。