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

时间:2015-02-18 11:25:40

标签: c# entity-framework

我有一个表UserForms,它有一个到Country表的两个外键,但在创建我的控制器和创建视图(对于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; }
 }

2 个答案:

答案 0 :(得分: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; }
}

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

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

  

{&#34; INSERT语句与FOREIGN KEY约束冲突   &#34; FK_dbo.DependentTable_dbo.PrincipalTable_Id&#34 ;.冲突   发生在数据库&#34; DatabaseName&#34;,table&#34; dbo.PrincipalTable&#34;,列   &#39;标识&#39 ;.声明已经终止。&#34;}

     

其他信息:保存实体时发生错误   不要为其关系公开外键属性。该   EntityEntries属性将返回null,因为单个实体不能   被确定为例外的来源。处理例外情况   通过公开外键属性可以使保存更容易   你的实体类型。有关详细信息,请参阅InnerException。

答案 1 :(得分:3)

@danludwig感谢你解释@ T.Glatzer回答这对我有用!谢谢。我现在正在使用的最终代码是

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

        public string FullNames { get; set; }
    [ForeignKey("IndividualsCountry")]
        public int? IndividualsCountryId { get; set; }
    [ForeignKey("BusinessCountry")]
        public int? BusinessCountryId { get; set; }

        public virtual Countries IndividualsCountry { get; set; }
    public virtual 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<UserForms> STRIndividualsCountry { get; set; }
        [InverseProperty("BusinessCountry")]
        public virtual ICollection<UserForms> STRBusinessCountry { get; set; }
    }