【发布时间】:2018-12-30 03:57:22
【问题描述】:
错误:
SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Recipe”中插入标识列的显式值。
Program.cs
- 我添加了两个类别“早餐”和“午餐”。
- 可以在那里制作一个属于“BreakFast”的新食谱
- 如果我尝试添加新食谱,我会收到错误消息。
class Program
{
static void Main(string[] args)
{
using (RecipesEntities context = new RecipesEntities())
{
//context.Categories.Add(new Category { Name = "Breakfast" });
//context.Categories.Add(new Category { Name = "Lunch" });
//new receipe and assign it to these two new categories
// 1. Using Id properties
//Category category = context.Categories.FirstOrDefault(c => c.Name == "Breakfast");
//context.Recipes.Add(new Recipe { Name = "Cereal", CategoryId = category.Id });
// 2. Recipe.Category navigation property
Category category = context.Categories.FirstOrDefault(c => c.Name == "Lunch");
context.Recipes.Add(new Recipe { Name = "Pizza", Category = category });
context.SaveChanges();
}
}
}
我的数据库设计
Recipe Data这里应该是披萨。
【问题讨论】:
-
你能分享你的食谱课吗?
-
public int Id { get;放; } 公共字符串名称 { 获取;放; } public Nullable
CategoryId { get;放; } 公共虚拟类别类别 { 获取;放; } -
您可以尝试将 [Key]-annotation 添加到您的 Id 并检查 this answer 是否有帮助。
-
我得到同样的错误:(
标签: c# entity-framework ado.net