0

例如,我有 2 个实体:

public class Department
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Employee> Employees { get; set; }
    public Employee Manager { get; set; }
}

public class Employee
{
    public Guid Id { get; set; }
    public string FullName { get; set; }

    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }
    public Guid DepartmentId { get; set; }
    public string Position { get; set; }
}

我知道我可以(正如我已经做过的那样:)Department.EmployeesEmployee.Id(反之:Employee.DepartmentDepartment.Id)相关联。

问题:
1)这是一两个协会吗?

2) 我可以在Department.Manager和之间创建第二个关联Employee.Id吗?不想将经理存储在另一个表中,因此它们也存储在 Employee 表中并在Position字段“Manager”中。

4

1 回答 1

1

定义如下关系。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Department>()
        .HasRequired(a => a.Manager)
        .WithMany()
        .HasForeignKey(a => a.EmployeeId);
}

如果您想要延迟加载和更改跟踪,您也希望它们是虚拟的。

public class Department
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
    public virtual Employee Manager { get; set; }
}
于 2013-05-09T14:35:21.527 回答