use*_*747 10 c#-4.0 entity-framework-6
我正在尝试为几个名为' Employee'和' 的表实现DbContext.Department员工和部门之间的关系是多对一的.即部门可以有很多员工.
下面是我设计的EntityFramework类(CodeFirst方法)
[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; }
}
Run Code Online (Sandbox Code Playgroud)
在添加员工记录时,我得到的是异常
"Invalid column name 'Department_ID1'."
Run Code Online (Sandbox Code Playgroud)
我不确定为什么EF指的是Department_ID1.我需要在OnModelCreating方法中添加配置DbContext吗?
我正在使用EF版本 6.1.1
use*_*747 11
喜花了一些时间,我可以通过解决这个问题ForeignKey的属性public virtual Department Department { get; set; }的财产Employee类.
请看下面的代码.
[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; }
}
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题.有没有其他解决方案来解决这个问题?使用流畅的API?
我在EF one-many交易中也遇到了这个问题,该交易one具有List的many属性,而我的映射未指定该属性。例如:
public class Notification
{
public long ID { get; set; }
public IList<NotificationRecipient> Recipients { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后
public class NotificationRecipient
{
public long ID { get; set; }
public long NotificationID { get; set; }
public Notification Notification { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后在我的映射中,导致Exception(错误方式)的方式:
builder.HasOne(x => x.Notification).WithMany()
.HasForeignKey(x => x.NotificationID);
Run Code Online (Sandbox Code Playgroud)
解决该问题的方法(正确的方法)是指定WithMany属性:
builder.HasOne(x => x.Notification).WithMany(x => x.Recipients)
.HasForeignKey(x => x.NotificationID);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6483 次 |
| 最近记录: |