System.Data.SqlClient.SqlException:无法将值NULL插入“IngredientId”列,表'RecipeApplicationDb.dbo.IngredientModels';

时间:2015-10-13 13:13:05

标签: c# sqlexception localdb

我一直在寻找一种为ASP.NET MVC应用程序自动生成ID的方法。这是因为我在尝试更新数据库时遇到此错误:

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? 有人能告诉我这是否是正确的解决方案,如果是这样,我应该把这段代码放在哪里。

提前致谢。

============= EDIT =====================

我还创建了一个包含以下内容的配置文件:

        #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

为了更新数据库,我使用Package Manager Console并使用以下命令:

Update-Database -Verbose -Force

此外,我将LocalDb用于此项目,数据库管理器是否找不到数据库。

3 个答案:

答案 0 :(得分:2)

在您定义模型添加的IngredientModel类中?在int之后如下所示:

public int? IngredientsId {get; set;}     

这应绕过允许您输入null的值(这样您可以在运行代码时检查它是否输入了值)。

如果输入为null,则删除数据注释[Key]。默认情况下,模型类中的第一行将是您的主键。

如果不起作用,请使用此注释[HiddenInput(DisplayValue = true)]

它没有解决它读取一些数据注释。

答案 1 :(得分:1)

在使用Microsoft SQL Server时,我多次遇到此问题,并且按照相同的方法进行修复。要解决此问题,请确保将身份规范设置为。外观如下:

Identity Specification 这样,列号通常会像主键一样自动递增。

如何?右键单击包含该列的表,选择设计选择主要键,然后在列属性窗口中找到身份规范,并将其设置为

答案 2 :(得分:0)

您可以在IngredientId字段中使用数据注释:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

希望它有所帮助。