EntityFramework:无效的列名称* _ID1 [英] EntityFramework : Invalid column name *_ID1
问题描述
我正在尝试为称为'Employee
'和'Department
'的几张表实现DbContext
员工与部门之间的关系是多对一的.即部门可以有很多员工.
I am trying to implement DbContext for couple of tables called 'Employee
' and 'Department
'
Relationship between Employee and Department is many to one. i.e. department can have many employees.
下面是我设计的EntityFramework类(CodeFirst方法)
Below are the EntityFramework classes I designed ( CodeFirst approach )
[Table("Employee")]
public class Employee
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Department_ID")]
public int Department_ID { get; set; }
public virtual Department Department { get; set; }
}
[Table("Department")]
public class Department
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Column("Name")]
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
在添加员工记录时,我遇到了异常
While adding Employee record I am getting below exception
"Invalid column name 'Department_ID1'."
我不确定为什么EF指的是Department_ID1
.我是否需要在DbContext
的OnModelCreating
方法中添加配置?
I am not sure why EF is referring to Department_ID1
. Do I need to add configuration in OnModelCreating
method of DbContext
?
我正在使用EF版本6.1.1
推荐答案
花了一些时间后,我可以通过在Employee
类的public virtual Department Department { get; set; }
属性上使用ForeignKey
属性来解决此问题.
Hi After spending some time I could fix this problem by using ForeignKey
attribute on public virtual Department Department { get; set; }
property of Employee
class.
请参见下面的代码.
[Table("Employee")]
public class Employee
{
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("Name")]
public string Name { get; set; }
[Column("Department_ID")]
public int Department_ID { get; set; }
[ForeignKey("Department_ID")]
public virtual Department Department { get; set; }
}
这解决了我的问题.还有其他解决方案可以解决此问题吗?使用流利的API?
This fixed my problem. Are there any other solution to fix this? Using fluent API?
这篇关于EntityFramework:无效的列名称* _ID1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!