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

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

    }

错误:

The ForeignKeyAttribute on property 'DID' on type 'MvcApplication1.Models.EmployeeModel' is not valid. The foreign key name 'DeptID' was not found on the dependent type 'MvcApplication1.Models.EmployeeModel'. The Name value should be a comma separated list of foreign key property names.

请帮助。提前致谢。

最佳答案

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

}

关于c# - Entity Framework Code First 中的外键名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31160110/

相关文章:

c# - dbo.Sometable 中的 dbo 是什么

c# - 是否可以将属性赋予 ExpectedException 中的消息?

c# - iFrame 在 asp AjaxToolkit TabContainer 中加载两次

c# - 在哪里添加 System.Windows.Media.GradientStopCollection 的引用

asp.net - 在回发时将 jQuery 与 ASP.NET Web 表单结合使用

c# - 序列化 JSON Dictionary<string, string>

javascript - 如何从 javascript (ajax) 调用 Web 服务

C# 无法转换为 'Microsoft.EntityFrameworkCore.DbContextOptions'

c# - LINQ 按子属性分组

c# - 如何将 EventHandler 与 SignalR 集线器与 .NET 核心相结合?