Entity Framework Code First中的外键名称错误

8
当我使用以下代码时,表格会成功生成并包含主键和外键关系。
 [Table("tblDepartments")]
    public class DepartmentModel
    {
        [Key]
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public ICollection<EmployeeModel> Employees { get; set; }
    }



    [Table("tblEmployees")]
    public class EmployeeModel
    {
        [Key]
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }      
        public virtual DepartmentModel DID { get; set; }

    }

但是当我使用以下代码时,我遇到了错误:
[Table("tblDepartments")]
    public class DepartmentModel
    {
        [Key]
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public ICollection<EmployeeModel> Employees { get; set; }
    }



    [Table("tblEmployees")]
    public class EmployeeModel
    {
        [Key]
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }     

        [ForeignKey("DeptID")]
        public virtual DepartmentModel DID { get; set; }

    }

错误:

MvcApplication1.Models.EmployeeModel 类型的属性 DID 上的 ForeignKeyAttribute 不是有效的。在从属类型 MvcApplication1.Models.EmployeeModel 上未找到外键名称 DeptID。Name 值应该是外键属性名称的逗号分隔列表。

请帮忙,谢谢。


4
请仔细查看消息的内容:Name值应该是一个逗号分隔的外键属性名称列表。 当DeptIDEmployeeModel的属性时,您可以使用此属性。 - Gert Arnold
3个回答

10

问题在于你的EmployeeModel中缺少departmentid字段,正如Gert所建议的那样。你可以使用以下内容来更新EmployeeModel。

[Table("tblEmployees")]
public class EmployeeModel
{
    [Key]
    public int EmployeeID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public string City { get; set; }     
    public int DeptID { get; set; } //<-- You forgot to add this
    [ForeignKey("DeptID")]
    public virtual DepartmentModel DID { get; set; }

}

4

将外键作为模型的属性,然后使导航属性指向它。

public class EmployeeModel
    {
        [Key]
        public int ID { get; set; }
        public int DeptID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string City { get; set; }     

        [ForeignKey("DeptID")]
        public virtual DepartmentModel DID { get; set; }

    }

0
在 '[ForeignKey("DeptID")]' 中,你需要在模型中拥有属性 DeptID。 如果你不想要它,而只是在外键字段上使用名称 DeptID,你需要使用流畅接口来配置关系,即:
        HasOptional(t => t.DID)
            .WithMany()
            .Map(d => d.MapKey("DeptID"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接