C# 实体框架中可选关系的可选

C# 实体框架中可选关系的可选,c#,entity-framework,entity-framework-5,C#,Entity Framework,Entity Framework 5,有人可以指导我在这个场景中使用ModelBuilder吗。我试过这样的方法: modelBuilder.Entity<User>() .HasOptional(f => f.Employee) .WithOptionalPrincipal(e => e.User); public class User { public int UserID {get; set;} public virtual Employe

有人可以指导我在这个场景中使用ModelBuilder吗。我试过这样的方法:

modelBuilder.Entity<User>()
        .HasOptional(f => f.Employee)
        .WithOptionalPrincipal(e => e.User);

public class User 
{
       public int UserID {get; set;}
       public virtual Employee employee{get; set;}
}
public class Employee 
{
       public int EmployeeID {get; set;}
       public int UserID {get; set;}
       public virtual User user {get; set;}
}
modelBuilder.Entity()
.has可选(f=>f.Employee)
.带有可选主体(e=>e.User);
公共类用户
{
public int UserID{get;set;}
公共虚拟员工{get;set;}
}
公营雇员
{
public int EmployeeID{get;set;}
public int UserID{get;set;}
公共虚拟用户用户{get;set;}
}

它不会获取员工数据。

解决您需求的方法是与独立关联建立一对多关系

public class User // Principal
{
    public int UserID { get; set; } // PK
    public virtual Employee Employee { get; set; }
}
public class Employee // Dependent
{
    public int EmployeeID { get; set; } // PK
    // public int UserID {get; set; } // remove to create independent association
    public virtual User User { get; set; }
}
配置

modelBuilder.Entity<User>()
    .HasOptional(u => u.Employee)
    .WithOptionalPrincipal(e => e.User);
将员工(1)与用户(1)关联

将员工(2)与用户(1)关联

当然,如果我们从数据库中手动更改它,它会工作,但在执行后EF上可能会出现意外行为

update Employees set User_UserId = 1

我认为可选关系没有可选关系,主体可能有可选的依赖关系,但依赖关系需要引用现有主体。除非是一对多关系,依赖关系可能有可选的主体。但在一对一或零的关系中,我恐怕这种关系(opt-to-opt)是不存在的。还有别的办法吗?
using (var db = new AppContext())
{
    var employee = db.Employees.Find(1);
    employee.User = db.Users.Find(1);
    db.SaveChanges();
}

 User            Employee
------     ----------------------
UserID     EmployeeID User_UserID
  1            1          1
               2         null
using (var db = new AppContext())
{
    var employee = db.Employees.Find(2);
    employee.User = db.Users.Find(1);
    db.SaveChanges();
}

 User            Employee
------     ----------------------
UserID     EmployeeID User_UserID
  1            1         null
               2          1
update Employees set User_UserId = 1