0

这些是我的实体:

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; }
}

部门有很多员工。每个用户只有一名员工(一对一)。我怎样才能首先与流利的代码建立这种关系?

谢谢。

4

1 回答 1

1

由于您没有使用共享主键,因此您可以将其映射为“一对多”关系并忽略“多”端。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        ...

        modelBuilder.Entity<User>()
         .HasRequired(u => u.Employee)
         .WithMany()
         .HasForeignKey(u => u.EmployeeId);

    }
于 2012-05-13T13:46:36.963 回答