【问题标题】:System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'IngredientId', table 'RecipeApplicationDb.dbo.IngredientModels';System.Data.SqlClient.SqlException:无法将值 NULL 插入到列“IngredientId”、表“RecipeApplicationDb.dbo.IngredientModels”中;
【发布时间】:2016-01-11 06:16:17
【问题描述】:

我一直在寻找一种为 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 表达式生成成分 ID。 为此,我发现(除其他外)这篇文章: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,数据库管理器没有找到数据库。

【问题讨论】:

  • 你关心值是多少吗?您只需将数据库配置为自动为您增加 ID:stackoverflow.com/questions/10991894/…
  • @user1666620 就我而言,我只需要一个唯一的 ID。
  • 我肯定会像@user1666620 建议的那样使用 SQL Server 的标识增量。它会抹去整个问题。
  • 根据代码,我可以看到使用 [Key] 定义的成分模型,但是您在 Create 方法中添加了 UnitOfMeasure。根据msdn.microsoft.com/en-us/data/jj591583.aspx,如果您使用 Code First,则会自动将整数键定义为自动生成...
  • 对此我很抱歉。似乎我在问题中输入了错误的控制器。在@DavidG 发表他的评论后,我现在改变了这一点。

标签: c# sqlexception localdb


【解决方案1】:

在您定义模型的成分模型类中添加? int之后如下图:

public int? IngredientsId {get; set;}     

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

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

如果这不起作用,请改用此注解[HiddenInput(DisplayValue = true)]

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

【讨论】:

    【解决方案2】:

    我在使用Microsoft SQL Server 时多次遇到此问题,我已按照相同的方法修复它。要解决此问题,请确保将 Identity Specification 设置为 Yes。这是它的样子:

    这样,列号会像主键一样自动递增。

    HOW?: 右键单击包含该列的表,选择设计选择主键并在 Column properties 窗口中找到 Identity Specification 并将其设置为 Yes

    【讨论】:

      【解决方案3】:

      您可以在 IngredientId 字段上使用数据注解:

      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-27
        • 2021-10-31
        • 2012-11-08
        相关资源
        最近更新 更多