Asp.net mvc MVC实体框架中保存父子表的有效方法
我正在尝试使用实体框架的MVC,并试图了解使用EF的最佳方法 我有一个可以保存学生信息和父亲/母亲信息的页面。我当前的代码工作正常,如下所示,但我觉得我做得不对。有没有更好的方法让我这么做?我需要调用SaveChanges()两次吗 db的结构如下:; 人 人格智力测验 名字Varchar(50) 学生 学生/人格国际FK 圣父人格 圣母玛利亚酒店 学生、父亲和母亲都在人桌旁 “注册”视图页面中有3个人的文本框:Asp.net mvc MVC实体框架中保存父子表的有效方法,asp.net-mvc,entity-framework,parent-child,Asp.net Mvc,Entity Framework,Parent Child,我正在尝试使用实体框架的MVC,并试图了解使用EF的最佳方法 我有一个可以保存学生信息和父亲/母亲信息的页面。我当前的代码工作正常,如下所示,但我觉得我做得不对。有没有更好的方法让我这么做?我需要调用SaveChanges()两次吗 db的结构如下:; 人 人格智力测验 名字Varchar(50) 学生 学生/人格国际FK 圣父人格 圣母玛利亚酒店 学生、父亲和母亲都在人桌旁 “注册”视图页面中有3个人的文本框: @Html.EditorFor(s => s.Person.FirstNam
@Html.EditorFor(s => s.Person.FirstName) @*student name*@
@Html.EditorFor(f => f.Father.FirstName) @*father name*@
@Html.EditorFor(f => f.Mother.FirstName) @*mother name*@
控制器代码如下所示
[HttpPost]
public ActionResult Register(Student sm)
{
using (var db = new SMEntities())
{
db.People.Add(sm.Person);
db.People.Add(sm.Mother);
db.People.Add(sm.Father);
db.SaveChanges(); //save the 3 persons
int studentId = sm.Person.PersonID;
int motherId = sm.Mother.PersonID;
int FatherId = sm.Father.PersonID;
Student s = new Student();
s.Student_PersonID = studentId;
s.Father_PersonID = FatherId;
s.Mother_PersonID = motherId;
db.Students.Add(s);
db.SaveChanges();
}
}
我使用的是VS2010、MVC 3,这是根据数据库第一个概念建模的。您实际上可以通过以下方式替换代码:
[HttpPost]
public ActionResult Register(Student sm)
{
using (var db = new SMEntities())
{
db.Students.Add(sm);
db.SaveChanges();
}
}
这样做的原因是,当您添加学生时,EF会将所有相关实体添加到上下文(未附加到上下文)。因此,此代码将把学生
、人
、父亲
和母亲
插入数据库,并且应该与您的代码完全相同