实体框架中可选关系的可选项

时间:2014-09-17 11:57:19

标签: c# entity-framework entity-framework-5

有人可以指导我在此方案中使用模型构建器。我试过这样的事情:

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

它无法获取员工数据。

1 个答案:

答案 0 :(得分:0)

根据您的要求解决的问题是与独立协会建立一对多关系。

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

生成的数据库将创建一对多关系。用户成为委托人,员工变为依赖,但员工可以选择委托人。

using (var db = new AppContext())
{
    // User can have optional Employee.
    db.Users.Add(new User { UserID = 1, Employee = null });
    db.SaveChanges();
}
using (var db = new AppContext())
{
    // Employee can have optional User.
    db.Employees.Add(new Employee { EmployeeID = 1, User = null });
    db.Employees.Add(new Employee { EmployeeID = 2, User = null });
    db.SaveChanges();
}

 User            Employee
------     ----------------------
UserID     EmployeeID User_UserID
  1            1         null
               2         null

将员工(1)与用户(1)联系起来。

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

将员工(2)与用户(1)联系起来。

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

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

update Employees set User_UserId = 1