2015-10-13 116 views
1

我一直在尋找一種方法來自動生成一個ASP.NET MVC應用程序的ID。這是因爲我在嘗試更新數據庫,當這個錯誤:System.Data.SqlClient.SqlException:無法將NULL值插入到'IngredientId'列中,表'RecipeApplicationDb.dbo.IngredientModels';

System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'IngredientId', table 'RecipeApplicationDb.dbo.IngredientModels'; 

這是在型號:

public class IngredientModel 
{ 
     [Key] 
     public int IngredientId { get; set; } 

     [Required] 
     public string Name { get; set; } 
} 

這是控制器:

public class IngredientController : Controller 
{ 
    private RecipeApplicationDb db = new RecipeApplicationDb(); 

    public ActionResult Index() 
    { 
     //var ingredients = db.Ingredients.Include(i => i.DefaultUOM); 
     return View(); 
    } 

    public ActionResult Create() 
    { 
     return View(); 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include = "IngredientId,Name,SeasonStartdate,SeasonEnddate")] IngredientModel ingredientModel) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Ingredients.Add(ingredientModel); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     ViewBag.IngredientId = new SelectList(db.UnitOfMeasures, "UnitOfMeasureId", "Name", ingredientModel.IngredientId); 
     return View(ingredientModel); 
    } 

    protected override void Dispose(bool disposing) 
    { 
     if (disposing) 
     { 
      db.Dispose(); 
     } 
     base.Dispose(disposing); 
    } 
} 

我認爲最好的方法解決這個問題是使用Linq表達式來生成IngredientId。 爲此,我發現(除其他外)這個職位:How do I use Linq to obtain a unique list of properties from a list of objects? 有人可以告訴我,如果這是正確的解決方案,如果是的話,我應該把這個代碼。

在此先感謝。

=============編輯=====================

我也創建一個配置文件與此內容:

 #region Ingredienten 

     var italiaanseHam = new IngredientModel { Name = "Italiaanse Ham", SeasonStartdate = DateTime.Now, SeasonEnddate = DateTime.Now }; 
     var zachteGeitenkaas = new IngredientModel { Name = "Zachte Geitenkaas", SeasonStartdate = DateTime.Now, SeasonEnddate = DateTime.Now }; 
     var gedroogdeVeenbessen = new IngredientModel { Name = "Gedroogde Veenbessen", SeasonStartdate = DateTime.Now, SeasonEnddate = DateTime.Now }; 
     var gemsla = new IngredientModel { Name = "Gemsla", SeasonStartdate = DateTime.Now, SeasonEnddate = DateTime.Now }; 
     var stilton = new IngredientModel { Name = "Stilton", SeasonStartdate = DateTime.Now, SeasonEnddate = DateTime.Now }; 

     if (!context.Ingredients.Any()) 
     { 
      context.Ingredients.AddOrUpdate(
       i => i.IngredientId, 
       italiaanseHam, 
       zachteGeitenkaas, 
       gedroogdeVeenbessen, 
       gemsla, 
       stilton 
       ); 
     }; 

     #region Recipes 
     var LittleGemsal = new RecipeModel 
     { 
      Name = "Little Gemsla", 
      Description = "Little Gemsla met geitenkaas, veenbessen, gedroogde ham en stilton", 
      ImageUrl = "http://google.com", 
      RecipeLines = new List<RecipeLine> { 
       new RecipeLine { Quantity = 1, UnitOfMeasure = plak, Ingredient = italiaanseHam }, 
       new RecipeLine { Quantity = 100, UnitOfMeasure = gram, Ingredient = zachteGeitenkaas }, 
       new RecipeLine { Quantity = 2, UnitOfMeasure = eetlepel, Ingredient = gedroogdeVeenbessen }, 
       new RecipeLine { Quantity = 4, UnitOfMeasure = stuks, Ingredient = gemsla }, 
       new RecipeLine { Quantity = 1, UnitOfMeasure = stuks, Ingredient = stilton }, 
      } 
     }; 

     if (!context.Recipes.Any()) 
     { 
      context.Recipes.AddOrUpdate(
       i => i.RecipeId, 
       LittleGemsal 
       ); 
     }; 
     #endregion 

,並更新我使用軟件包管理器控制檯使用以下命令數據庫:

Update-Database -Verbose -Force 

而且我用的LocalDB這個項目,做數據庫管理器不會找到數據庫。

+2

你關心什麼是價值?您可以將數據庫配置爲自動爲您添加ID:http://stackoverflow.com/questions/10991894/auto-increment-primary-key-in-sql-server-management-studio-2012 – user1666620

+0

@ user1666620 As far就我而言,我只需要一個唯一的ID。 –

+0

我肯定會使用SQL Server的身份增量,如@ user1666620建議。它會消除整個問題。 –

回答

1

在您定義模型的IngredientModel類中添加?如下圖所示INT後:

public int? IngredientsId {get; set;}  

這應該繞過值允許你輸入空(這樣你就可以檢查它是否正進入一個值,當你運行你的代碼)。

如果輸入爲空,則刪除數據註釋[Key]。默認情況下,模型類中的第一行將是您的主鍵。

如果這不起作用,請使用此註釋代替[HiddenInput(DisplayValue = true)]

它沒有解決它讀取一些數據註釋。

0

您可以在IngredientId字段中使用數據adnotation:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)

希望它能幫助。

+0

這不應該是一個整數的[Key]列所需要的... –

相關問題