【发布时间】:2015-07-25 20:59:12
【问题描述】:
我正在开发一个 asp.net mvc Web 应用程序 + Entity Framework 6.0。我已经使用 EF Db-Context 在我的 Web 应用程序中映射了我的数据库表。我有两个模型类 Emp & Dept 如下:-
public partial class Dept
{
public Dept()
{
this.Emps = new HashSet<Emp>();
}
public int DeptID { get; set; }
public string DName { get; set; }
public virtual ICollection<Emp> Emps { get; set; }
}
//----
public partial class Emp
{
public Emp()
{
this.Accounts = new HashSet<Account>();
}
public int EMPID { get; set; }
public string name { get; set; }
public int DeptID { get; set; }
public virtual Dept Dept { get; set; }
public virtual ICollection<Account> Accounts { get; set; }
}
现在需要Emp.DeptID FK,所以我编写了以下测试方法来测试 EF 是否足够聪明以重新排序添加操作:-
public ActionResult Index()
{
Dept d = new Dept() { DName="test5"};
Emp e = new Emp() { name="test5test5"};
t.Emps.Add(e);
d.Emps.Add(e);
t.Depts.Add(d);
t.SaveChanges();
return Content("5");
}
现在我虽然上述方法会引发异常,因为我已经定义在添加部门之前添加t.Emps.Add(e);,这应该引发 Emp.DeptID 不能为零的异常(因为没有任何部门与零身份)。但实际发生的情况是 Dept 和 Emp 都被添加了,所以我的问题是 EF 是如何处理上述方法的?唯一有效的方法是 EF 先添加了部门,这与我指定的顺序不同?
【问题讨论】:
标签: c# entity-framework entity-framework-6 dbcontext