开发者

Entity Framework creating null entry in the DB on POST

I've got a simple form that creates Categories with a name a开发者_JAVA百科nd a List of Cars assigned to them.

Everything works fine minus the fact that for each entry in the DB I get a second one before that is null everywhere except for the parent BrandId.

[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 });
}

My repository method is:

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

    _context.SaveChanges();

    return category;
}

As you can see it's a pretty straight forward POST, yet every time I create a Category, I get two entries:

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

My trick has been to simply go through the table and remove any Category that has null values in Name. But that's obviously not resolving the actual issue.


As per the comments, It is actually your GET that will be creating the blank record when it passes a new Category() to the view.
Some of the ORM's detect new'd up objects and add them to your context for you. Which helpfully creates confusing issues like this one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜