【发布时间】: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