我收到了'EntityCommandExecutionException
'和
执行命令定义时发生错误。有关详细信息,请参阅内部异常。
内部消息
无效的列名'Department_ID'
这似乎是从这行代码执行的查询:
List<Employee> _employees = employeeContext.Employees.ToList();
SELECT [Extent1].[EmployeeID] AS [EmployeeID],
[Extent1].[Name] AS [Name],
[Extent1].[Gender] AS [Gender],
[Extent1].[City] AS [City],
[Extent1].[DepartmentID] AS [DepartmentID],
[Extent1].[DateOfBirth] AS [DateOfBirth],
[Extent1].[Department_ID] AS [Department_ID]
FROM [dbo].[tblEmployee] AS [Extent1]
考虑到没有Department_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; }
}
不确定该怎么做。有什么想法吗?
答案 0 :(得分:2)
Department_ID将根据您的部门类中的关系而来。您有一个List Employees,它会自动在Employee表中假定一个名为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; }
}
我还建议您将List维护为虚拟。