C# 保存更改的方法失败
我有一种创造新奶油的post方法C# 保存更改的方法失败,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我有一种创造新奶油的post方法 public ActionResult CreateCream(CreamModel cream, string creamTypeId) { if (ModelState.IsValid) { if (creamTypeId != string.Empty) { try {
public ActionResult CreateCream(CreamModel cream, string creamTypeId)
{
if (ModelState.IsValid)
{
if (creamTypeId != string.Empty)
{
try
{
cream.CreamTypeModel_id = int.Parse(creamTypeId);
creamManager.CreateCream(cream);
TempData["message"] = string.Format("Игрок {0} сохранен", cream.Name);
return RedirectToAction("Index", "Home");
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}
}
ViewBag.ChoosingCreamType = GetCreamSelectList();
return View(cream);
}
当我打电话时
public void CreateCream(CreamModel newCream)
{
if (newCream.Id == 0)
{
context.CreamModels.Add(newCream);
context.SaveChanges();
}
}
当我调用context.SaveChanges时,代码失败,我转到视图,而不是重定向!我不明白为什么它不起作用?若我删除SaveChanges,它会执行,但不会保存在数据库中
我的模型
public class CreamModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string ImageName { get; set; }
public int? CreamTypeModel_id { get; set; }
public CreamTypeModel CreamTypeModel { get; set; }
}
错误消息
SqlException:列名称“CreamTypeModel_id”指定得更多
在INSERT的SET子句或列列表中不止一次。纵队
不能在同一子句中指定多个值。修改
子句以确保列只更新一次。如果这
语句更新或向视图中插入列,可以使用列别名
隐藏代码中的重复项
我想到的问题是,您没有关联FK就有了关系:
public class CreamModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string ImageName { get; set; }
[ForeignKey("CreamTypeModel")]
public int? CreamTypeModel_id { get; set; }
public virtual CreamTypeModel CreamTypeModel { get; set; }
}
这会将FK链接到关联的引用特性 错误消息是什么?它是如何失败的?错误是什么?当我调用context.SaveChanges时,代码失败,我总是去查看,这意味着您的模型数据无效。TanvirArjel-但是为什么?我不使用数据注释并进行任何验证,而且a几乎有1个十进制问题,因为我采用本机验证错误值“1.22”对价格无效。字段Price必须是一个数字,我不能写点或逗号,但我实际使用的是整数。还有其他我不知道的问题。在调试器下分析ModelState,它会告诉你这个问题。