Asp.net mvc 如何在实体框架中更新嵌套列表?
我找不到如何更新我的估计行Asp.net mvc 如何在实体框架中更新嵌套列表?,asp.net-mvc,entity-framework,valueinjecter,Asp.net Mvc,Entity Framework,Valueinjecter,我找不到如何更新我的估计行 public class EstimateLine { [Key] [Column(Order = 0)] public virtual int EstimateId { get; set; } [Key] [Column(Order = 1)] public virtual int LineId { get; set; } public virtual float Price { get; set; } }
public class EstimateLine
{
[Key]
[Column(Order = 0)]
public virtual int EstimateId { get; set; }
[Key]
[Column(Order = 1)]
public virtual int LineId { get; set; }
public virtual float Price { get; set; }
}
这是估价课
public class Estimate
{
public virtual int EstimateId { get; set; }
public virtual float TotalPrice { get; set; }
public virtual IList<EstimateLine> Lines { get; set; }
]
公共类估算
{
公共虚拟整数估计ID{get;set;}
公共虚拟浮动总价{get;set;}
公共虚拟IList行{get;set;}
]
这是编辑
public ActionResult Edit(EstimateViewModel estimateView)
{
var estimate = db.Estimates.FirstOrDefault(e => e.EstimateId == estimateView.EstimateId);
if (ModelState.IsValid)
{
estimate.InjectFrom(estimateView);
var lines = new List<EstimateLine>();
lines.InjectFrom(estimateView.Lines);
estimate.Lines = lines;
db.SaveChanges();
return RedirectToAction("Index");
}
}
公共操作结果编辑(estimateView模型estimateView)
{
var estimate=db.Estimates.FirstOrDefault(e=>e.EstimateId==estimateView.EstimateId);
if(ModelState.IsValid)
{
估计。从(估计视图)中输入;
变量行=新列表();
lines.InjectFrom(estimateView.lines);
估计。行=行;
db.SaveChanges();
返回操作(“索引”);
}
}
这里它没有删除数据库中的前一行,所以我得到了重复的键错误。我如何告诉EF删除前一个估算行?以下是我自己最终创建的代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EstimateViewModel estimateView)
{
var estimate = db.Estimates.Find(estimateView.EstimateId);
if (estimate == null)
ModelState.AddModelError(String.Empty,"Unknown estimate number");
if (ModelState.IsValid)
{
// Remove for lines from DB
estimate.Lines.ToArray().ForEach(line => db.EstimateLines.Remove(line));
// Map user input
estimate.InjectFrom<DeepCloneInjection>(estimateView);
// Update in db
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DbEntityValidationException dbEx)
{
foreach (var error in dbEx.EntityValidationErrors.SelectMany(entityValidationErrors => entityValidationErrors.ValidationErrors))
{
ModelState.AddModelError(string.Empty, error.ErrorMessage);
}
}
}
return View("Create", estimateView);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果编辑(EstimateViewModel estimateView)
{
var estimate=db.Estimates.Find(estimateView.EstimateId);
如果(估计==null)
AddModelError(String.Empty,“未知估计数”);
if(ModelState.IsValid)
{
//删除数据库中的行
estimate.Lines.ToArray().ForEach(line=>db.EstimateLines.Remove(line));
//映射用户输入
估计。从(估计视图)中输入;
//数据库中的更新
尝试
{
db.SaveChanges();
返回操作(“索引”);
}
catch(DbEntityValidationException dbEx)
{
foreach(dbEx.EntityValidationErrors.SelectMany中的var错误(EntityValidationErrors=>EntityValidationErrors.ValidationErrors))
{
AddModelError(string.Empty,error.ErrorMessage);
}
}
}
返回视图(“创建”,估计视图);
}