实体框架代码优先中的Foreignkey Name错误

本文关键字:Foreignkey Name 错误 框架 代码 实体 | 更新日期: 2023-09-27 18:00:41

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

 [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值应为外键属性名称的逗号分隔列表。

请帮忙。提前谢谢。

实体框架代码优先中的Foreignkey Name错误

问题出在EmployeeModel上,因为您的表中缺少Gert建议的departmentid字段。您可以使用下面的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; }
}

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

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

在'[ForeignKey("DeptID")]'中,您需要在模型中具有属性DeptID。如果你不想要它,只需要外键字段上的名称DeptID,你需要使用fluent接口来配置关系,即

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