繁体   English   中英

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

[英]Foreignkey Name error in Entity Framework Code First

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

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

请帮忙。 提前致谢。

问题出在您的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; }

}

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

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,则需要使用流畅的界面来配置关系,即

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM