关于MVC的一对多问题

时间:2016-01-07 07:03:31

标签: asp.net-mvc entity-framework

一般来说,EF,MVC和数据库的新手。如果这是非常明显的,请告诉我这究竟是什么,我很高兴在这里查看。

我无法将从Foreign Key计算的信息应用到我的Primary key。 换句话说:每当我们"销售"时,我试图通过展位计算并应用新的AmountMade。古董。
展台型号:

public class Booth
{

    public Booth()
    {
       Antiques = new List<Antique>();
    }

    [Required]
    public int BoothId { get; set; }

    [Required]
    public string Owner { get; set; }

    public double  AmountMade { get; set; }

    public Antique Antique {get;set;}

    public virtual ICollection<Antique> Antiques{get;set;}
}

古董模型:

public class Antique
{
    [Required]
    public int AntiqueId { get; set; }

    [Required]
    public string ItemName { get; set; }

    [Required]
    public double Price { get; set; }

    public bool Sold { get; set; }

    public int BoothId { get; set; }

    [ForeignKey("BoothId")]
    public virtual Booth Booth { get; set; }
}

AntiquesController:

    // GET: Antiques/Sell/5
    public ActionResult Sell(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Antique antique = db.Antiques.Find(id);
         antique.Booth.AmountMade = antique.Booth.AmountMade + antique.Price;   //Price of antique is added to Amount made 
        if (antique == null)
        {
            return HttpNotFound();
        }

         ViewBag.BoothId = new SelectList(db.Booths, "BoothId", "Owner", antique.BoothId);

        return View(antique);
    }

    // POST: Antiques/Sell/5

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Sell([Bind(Include = "AntiqueId,ItemName,Price,BoothId")] Antique antique)
    {
        if (ModelState.IsValid)
        {
            db.Entry(antique).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        } 
        antique.Sold = true;                                                    //Mark as sold
        ViewBag.BoothId = new SelectList(db.Booths, "BoothId", "Owner", antique.BoothId); 
        antique.Booth.AmountMade = antique.Booth.AmountMade + antique.Price;   //Price of antique is added to Amount made 

        return View(antique);
    }

1 个答案:

答案 0 :(得分:0)

这种同步发生在调用Db.SaveChanges()之后,但我不确定在此之前是否可以通过调用其他方法来完成。