这些是我的实体:
public class Department
{
public Department()
{
Employees = new List<Employee>();
}
public int ID { get; set; }
public string Name { get; set; }
public IList<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int DepartmentID { get; set; }
public Department Department { get; set; }
}
public class User
{
public int ID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int EmployeeID { get; set; }
public Employee Employee { get; set; }
}
部门有很多员工。每个用户都有只一名员工(一对一)。我怎样才能首先用流畅的代码实现这种关系呢?
感谢名单。
答案 0 :(得分:1)
由于您没有使用共享主键,因此可以将其映射为“一对多”关系,并忽略“多个”侧。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Entity<User>()
.HasRequired(u => u.Employee)
.WithMany()
.HasForeignKey(u => u.EmployeeId);
}