EF 6如何将两个外键设置为同一个表

Mar*_*ugu 7 c# entity-framework

我有一个表UserForms,它有一个States表的两个外键,但在创建我的控制器和创建视图(对于UserForms模型)时,不会出现链接到外键的两个字段.我应该怎么做才能解决这个问题?以下是两种型号:

public class UserForms
{
     public int Id { get; set; }

     public string FullNames { get; set; }
     public Countries IndividualsCountry { get; set; }
     public Countries BusinessCountry { get; set; }
}

public class Countries
{
     public Countries()
     {
         this.STRBusinessCountry = new HashSet<UserForms>();
         this.STRIndividualsCountry = new HashSet<UserForms>();
     }

     public int Id { get; set; }
     public string NameOfCountry { get; set; }

     [InverseProperty("IndividualsCountry")]
     public virtual ICollection<UserForm> STRIndividualsCountry { get; set; }
     [InverseProperty("BusinessCountry")]
     public virtual ICollection<UserForm> STRBusinessCountry { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

dan*_*wig 8

@ T.Glatzer留下的评论是正确的.您应该在依赖实体上公开外键属性:

public class UserForms
{
    public int Id { get; set; }

    public string FullNames { get; set; }

    public int IndividualsCountryId { get; set; }
    [ForeignKey("IndividualsCountryId")]
    public virtual Countries IndividualsCountry { get; set; }

    public int BusinessCountryId { get; set; }
    [ForeignKey("BusinessCountryId")]
    public virtual Countries BusinessCountry { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在这里我使用过int,但如果这些导航属性中的任何一个是可选的,你只需要替换int?System.Nullable<int>替换(这将int NULL在数据库中创建一个列而不是一个列int NOT NULL).

虽然EF不要求您公开导航属性,但通常是一个好习惯.相信我.它将帮助您以后避免意外的异常.事实上,一些EF异常消息实际上建议在实体类上公开外键属性,以帮助EF更好地弄清楚如何映射关系.以下是一个此类例外的示例.注意"附加信息"部分:

{"INSERT语句与FOREIGN KEY约束冲突"FK_dbo.DependentTable_dbo.PrincipalTable_Id".冲突发生在数据库"DatabaseName",表"dbo.PrincipalTable",列'Id'.语句已被终止."}

附加信息:保存不公开其关系的外键属性的实体时发生错误.EntityEntries属性将返回null,因为无法将单个实体标识为异常的来源.通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常.有关详细信息,请参阅InnerException.