2011-10-06 111 views
1

我有一個簡單的表單,創建一個名稱和分配給它的汽車列表的類別。實體框架在數據庫中創建空條目

一切工作正常減去一個事實,即對於數據庫中的每個條目,我得到第二個之前,除了父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 }); 
} 

我的資料庫的方法是:

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 

我的訣竅是簡單地瀏覽表格並刪除名稱中具有空值的任何類別。但這顯然不能解決實際問題。

+1

你的匹配GET也'返回查看(新類別{});'我會說這是正在保存的記錄。你可以通過設置其他屬性來檢驗我的理論,看看它是否出現在空白記錄中。 –

+0

可能是你正在調用你的'Post'方法兩次。你有沒有檢查它是否有中斷點? –

+0

@Jayantha,是的,這已經檢查過,並沒有發生。 – LanFeusT

回答

1

根據評論,它實際上是您的GET將創建空白記錄,當它通過new Category()到視圖。
某些ORM會檢測新對象並將它們添加到您的上下文中。這有助於創建像這樣的混淆問題。

+0

再次感謝! :) – LanFeusT