【问题标题】:Relation of entities?实体关系?
【发布时间】:2012-05-21 06:40:24
【问题描述】:

这些是我的实体:

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

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

谢谢。

【问题讨论】:

  • 每个用户都有一个员工还是每个用户都是一个员工?如果后者是真的,我会让 Employee 继承自 User。

标签: c# entity-framework foreign-keys ef-code-first code-first


【解决方案1】:

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

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

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

    }

【讨论】:

    猜你喜欢
    • 2017-01-06
    • 2012-06-23
    • 2011-12-29
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多