【问题标题】:Entity Framework creating null entry in the DB on POST实体框架在 POST 上的数据库中创建空条目
【发布时间】:2011-12-02 16:00:59
【问题描述】:

我有一个简单的表单,可以创建带有名称和分配给它们的汽车列表的类别。

除了父 BrandId 之外,对于数据库中的每个条目,我得到的第二个条目在所有地方都为 null。

[HttpPost]
public ActionResult AddNewCategory(AddNewCategoryPostViewModel categoryInfo)
{
    var brand = _repository.GetBrandById(categoryInfo.BrandId);
    if (categoryInfo.Name == null || categoryInfo.Cars == null)
    {
        if (categoryInfo.Name == null)
        {
            ModelState.AddModelError("Name", "The name cannot be empty.");
        }

        if (categoryInfo.Cars == null)
        {
            ModelState.AddModelError("Cars", "At least one car must be selected.");
        }

        var cars = _insplib.GetDevCategorysForProject((int)brand.Id);

        ViewBag.Cars = cars;
        ViewBag.Selectedcars = categoryInfo.Cars;

        return View(new Category()
                        {
                            Brand = brand
                        });
    }

    var category = new Category()
                        {
                            DateEntered = DateTime.Now,
                            IsArchived = false,
                            Name = categoryInfo.Name,
                            BrandId = categoryInfo.BrandId
                        };

    _repository.AddOrUpdateCategory(category);

    // more code here added to add the cars, but not relevant to this issue.

    return RedirectToRoute("Category", new { brand = category.Brand.ShortName, categoryId = category.Id });
}

我的仓库方法是:

public Category AddOrUpdateCategory(Category category)
{
    if (category.Id == 0)
        _context.AddToCategorys(category);

    _context.SaveChanges();

    return category;
}

如您所见,这是一个非常简单的 POST,但每次我创建一个类别时,我都会得到两个条目:

ID  Name    DateEntered IsArchived  
5   NULL    NULL    NULL    4
6   NewCategory 10/6/2011   False   4

我的诀窍是简单地遍历表并删除名称中具有空值的任何类别。但这显然不能解决实际问题。

【问题讨论】:

  • 你的匹配 GET 是否也 return View(new Category{}); 我会说这是正在保存的记录。您可以通过设置其他属性之一来测试我的理论,看看它是否显示在空白记录中。
  • 可能你调用了你的Post 方法两次。你用断点检查了吗?
  • @Jayantha,是的,已经检查过了,但没有发生。
  • @ChrisSainty,你是对的!那是我的问题。我没有传递新的类别,而是使用 ViewBag 仅传递我页面上标题和 ID 所需的 Brand 对象!谢谢!将您的解决方案作为答案,我会这样标记它:)

标签: asp.net-mvc-3 entity-framework linq-to-entities


【解决方案1】:

根据 cmets,实际上是您的 GET 在将 new Category() 传递给视图时创建空白记录。
一些 ORM 会检测新的对象并将它们添加到您的上下文中。这有助于产生像这样的令人困惑的问题。

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多