using (DataContext dbcontext=new DataContext ())
{
//emp.department.ID = dep.ID;
//emp.department = dep;
/*foreach (var item in dep.employees)
{
item.department.ID = dep.ID;
dbcontext.employees.Add(item);
dbcontext.SaveChanges();
}*/
int did = dep.ID;
Department dep1 = new Department();
dep1 = dbcontext.dempartments.Find(did);
Employee emp1 = new Employee();
emp1 = emp;
emp1.department = dep1;
dbcontext.employees.Add(emp1);
dbcontext.SaveChanges();
return RedirectToAction("List");
}
-------------------------------
外键实体保存数据代码:
using (DataContext dbcontext=new DataContext ())
{
int did = droplist;
Department dep = new Department();
dep = dbcontext.dempartments.Find(did);//先找到外键实体
emp.department = dep;//因为emp中外键是一个实体,所以你要给实体,不能只给ID外键。
dbcontext.employees.Add(emp);
dbcontext.SaveChanges();
return RedirectToAction("List");
}