我正在针对两种情况调试此方法:一种是有父级,另一种是没有父级。
如果没有父级,新的 Person 的 id 为 0,但实际上从未保存到数据库中。
如果有父级,则在此方法中新的 Person 的 id 为 0,但会以正确的值(比表中最高的值多 1)将一条新记录插入到数据库中。
这是怎么回事?我知道我做错了什么,但我不确定是什么。
我正在使用 EF Codefirst。
Controller 方法的代码:
[HttpPost]
public ActionResult Create(CreatePersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var parent = _db.Persons.FirstOrDefault(s => s.PersonId == viewModel.ParentId);
var person = new Person() { Name = viewModel.Name };
// if it has a parent, build new relationship
if (parent != null)
{
person.Parent = parent;
parent.Children.Add(person);
};
_db.Save();
return RedirectToAction("detail", "person", new { personId = person.PersonId });
}
return View(viewModel);
}
最佳答案
If there is no parent, the new Person has an id of 0 but never actually gets saved to the db.
那是因为您从未告诉 EF 它应该保留该实体。您只需创建一个 new Person()
即可。
你应该这样做:
dbContext.AddToPersons(person);
在调用dbContext.SaveChanges()
之前。
在存在父级的情况下,由于与parent
的关系,person
会被保存。
更新
我突然想到:如果您首先编写代码,则数据上下文中可能没有可用的 AddToPersons(...)
方法。如果是这样,您可以使用 dbContext.Persons.AddObject(person) 来代替。
关于asp.net-mvc - MVC4 中 Create() 方法的奇怪行为 - 新对象设置为 ID = 0,另存为其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925096/