我有一个表UserForms,它有两个指向Countries表的外键,但是在创建控制器和创建视图(对于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; }
 }发布于 2015-02-18 11:47:31
@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更好地了解如何映射关系。下面是这样一个例外的例子。注:“补充资料”一节:
{“插入语句与外键约束"FK_dbo.DependentTable_dbo.PrincipalTable_Id".冲突在数据库"DatabaseName”、表"dbo.PrincipalTable“、列'Id‘中发生冲突。语句已终止。” 附加信息:保存未公开外键属性的实体时发生错误。EntityEntries属性将返回null,因为无法将单个实体标识为异常的源。通过在实体类型中公开外键属性,可以更容易地处理保存过程中的异常。有关细节,请参阅InnerException。
发布于 2015-02-18 11:56:32
@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; }
    }https://stackoverflow.com/questions/28582454
复制相似问题