实体框架代码中的外键名称错误

时间:2015-07-01 11:32:54

标签: c# asp.net entity-framework

当我使用以下代码时,使用主键和外键关系成功生成表。

 [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; }

    }

错误:

  

类型上属性'DID'的ForeignKeyAttribute   'MvcApplication1.Models.EmployeeModel'无效。外键   在依赖类型上找不到名称“DeptID”   'MvcApplication1.Models.EmployeeModel'。 Name值应为a   以逗号分隔的外键属性名称列表。

请帮助。提前谢谢。

3 个答案:

答案 0 :(得分:6)

问题在于您的EmployeeModel,因为您缺少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; }

}

答案 1 :(得分:2)

将外键作为属性放入模型中,然后让导航属性指向它。

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; }

    }

答案 2 :(得分:0)

在'[ForeignKey(“DeptID”)]'中,你需要在模型中拥有属性DeptID。 如果您不想要它而只需要外键字段上的DeptID名称,则需要使用流畅的界面来配置关系,即

        HasOptional(t => t.DID)
            .WithMany()
            .Map(d => d.MapKey("DeptID"));