MVC实体框架中保存父子表的有效方法
我正在尝试使用 Entity Framework 进行 MVC,并尝试了解使用 EF 的最佳方法。
我有一个页面,可以保存学生的信息以及父亲/母亲的信息。我当前的代码可以工作,如下所示,但我觉得我没有正确执行此操作。我有更好的方法来做到这一点吗?我需要调用 SaveChanges() 两次吗?
数据库的结构如下; 人 PersonID INT PK 名字 Varchar(50)
学生 Student_PersonID INT FK Father_PersonID INT FK Mother_PersonID INT FK
学生、父亲和母亲对于 person 表都是 FK。
注册视图页面有 3 个人的文本框:
@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,这是根据数据库优先概念建模的。
I am trying out MVC with Entity Framework and I am trying to understand the best ways to use EF.
I have a page where student’s info together with the father/mother info can be saved. My current code works, as shown below, but I feel like I am not doing this correctly. Is there a better way for me to do this? Do I need to call SaveChanges() twice?
The db is structured as follows;
Person
PersonID INT PK
FirstName Varchar(50)
Student
Student_PersonID INT FK
Father_PersonID INT FK
Mother_PersonID INT FK
The student, father and mother are all FK to the person table.
The registration view page has textboxes for the 3 persons:
@Html.EditorFor(s => s.Person.FirstName) @*student name*@
@Html.EditorFor(f => f.Father.FirstName) @*father name*@
@Html.EditorFor(f => f.Mother.FirstName) @*mother name*@
The controller code looks like this
[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();
}
}
I am using VS2010, MVC 3, and this was modeled after the database first concept.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上可以将代码替换为:
这样做的原因是,当您添加
Student
时,EF 会将所有相关实体添加到上下文(未附加到上下文)。因此,此代码会将Student
、Person
、Father
和Mother
插入数据库,并且应该执行完全相同的操作就像你的代码一样。You can actually replace your code by:
The reason why this works is that EF will add all related entities to the context (which are not attached to the context) when you add the
Student
. So, this code will insertStudent
,Person
,Father
andMother
into the database and should do exactly the same like your code.