[英]ASP.Net MVC EF - Adding a Child on Parent Create
I have an MVC project with a Person class. 我有一个带有Person类的MVC项目。 The Model, Controller, and basic CRUD Views are established and working.
模型,控制器和基本CRUD视图已建立并正常工作。
The project contains a Notes class that allows a one-to-many Person/Notes relationship. 该项目包含一个Notes类,该类允许一对多的Person / Notes关系。 The Notes table stores all of the notes for a variety of entities in the system, so it is related via an EntityGuid.
注释表存储了系统中各种实体的所有注释,因此它通过EntityGuid关联。
The Note model is very basic: Note模型非常基本:
public class Note {
public int ID { get; set; }
public Guid EntityGuid { get; set; }
public string NoteBody { get; set; }
}
As is the Person Controller's Create method for the POST: 与人员控制器的POST的Create方法一样:
if (ModelState.IsValid) {
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
When creating a person, the Create View has a TinyMCE editor attached to a textarea
to record the note. 创建人员时,创建视图在
textarea
上附加了TinyMCE编辑器以记录注释。 I need the ability to save an initial note (optional) at the time the Person record is saved. 我需要能够在保存“个人”记录时保存初始注释(可选)。 This would be a child record to the Person, linked via EntityGuid to parent.
这将是Person的子记录,并通过EntityGuid链接到parent。
What is the cleanest/correct way to handle this under code-first ASP.Net MVC EF? 在代码优先的ASP.Net MVC EF下处理此问题的最干净/正确的方法是什么?
If you have the collection of notes defined in your Person class this should do the trick: 如果您在Person类中定义了注释集合,则应该这样做:
var note = new Note{NoteBody=noteFromModel};
if(person.Notes==null)
person.Notes=new List<Note>();
person.Notes.Add(note);
db.Persons.Add(person);
db.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.