C# EntityFramework更改我的查询-EntityCommandExecutionException
我得到一个“C# EntityFramework更改我的查询-EntityCommandExecutionException,c#,entity-framework,asp.net-mvc-4,C#,Entity Framework,Asp.net Mvc 4,我得到一个“EntityCommandExecutionException”,并且 执行命令定义时出错。有关详细信息,请参见内部异常 带着内心的信息 列名“部门ID”无效 这似乎是从以下代码行执行的查询: List<Employee> _employees = employeeContext.Employees.ToList(); 考虑到没有部门ID,这是错误的,我不知道这是从哪里来的。这是Employee类模型: [Table("tblEmployee")] public cla
EntityCommandExecutionException
”,并且
执行命令定义时出错。有关详细信息,请参见内部异常
带着内心的信息
列名“部门ID”无效
这似乎是从以下代码行执行的查询:
List<Employee> _employees = employeeContext.Employees.ToList();
考虑到没有部门ID,这是错误的,我不知道这是从哪里来的。这是Employee类模型:
[Table("tblEmployee")]
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DepartmentID { get; set; }
public DateTime DateOfBirth { get; set; }
}
[Table("tblDepartment")]
public class Department
{
public Int16 ID { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
[表(“tblEmployee”)]
公营雇员
{
public int EmployeeID{get;set;}
公共字符串名称{get;set;}
公共字符串{get;set;}
公共字符串City{get;set;}
public int DepartmentID{get;set;}
公共日期时间出生日期{get;set;}
}
[表(“待定部门”)]
公共课系
{
公共Int16 ID{get;set;}
公共字符串名称{get;set;}
公共列表雇员{get;set;}
}
不知道该怎么办。有什么想法吗?这个系的ID是根据你们系班级的关系来的。这里有一个员工列表,它会自动假定员工表中有一个名为Department_ID的列 您需要做的是在Employee表中添加一个名为Department的虚拟属性,而不是添加DepartmentID
[Table("tblEmployee")]
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public virtual Department Department { get; set; }
public DateTime DateOfBirth { get; set; }
}
如果需要将列名维护为DepartmentID,或者需要在代码中访问属性DepartmentID,则需要使用ForeignKey属性,如下所示:
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public DateTime DateOfBirth { get; set; }
}
我还建议您将列表维护为虚拟。是否使用CodeFirst生成表?