如何更新Entity Framework中的嵌套列表?

时间:2013-09-04 19:55:38

标签: asp.net-mvc entity-framework valueinjecter

我找不到如何更新我的EstimateLine

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; }
}

这是Estimate类

public class Estimate
{
    public virtual int EstimateId { get; set; }

    public virtual float TotalPrice { get; set; }

    public virtual IList<EstimateLine> Lines { 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");

        }
}

这里没有删除DB中的上一行,所以我遇到了重复的键错误。如何告诉EF删除以前的估算线?

1 个答案:

答案 0 :(得分:1)

这是我最终自己创建的代码:

    [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);
    }