asp.net-mvc - MVC4 中 Create() 方法的奇怪行为 - 新对象设置为 ID = 0,另存为其他内容

标签 asp.net-mvc entity-framework ef-code-first

我正在针对两种情况调试此方法:一种是有父级,另一种是没有父级。

如果没有父级,新的 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/

相关文章:

asp.net-mvc - 如何在运行代码之前等待所有任务完成

c# - 找不到 VS 2017 元数据文件 '.dll

asp.net-mvc - 单元测试 aspx View

asp.net - Web.config 中使用附加 .mdf 数据库的数据库连接字符串不起作用

linq - ef cf linq 填充被忽略的属性

c# - 无法使 EF Code First 使用手动更改的数据库

c# - 我可以迁移到 Entity Framework 中没有迁移的情况下创建的数据库吗?

javascript - 编译转换 : The type or namespace name could not be found when running TypeLite. tt

c# - Entity Framework 延迟加载不起作用

c# - 改进 LINQ to EF 生成的 SQL 查询