更新实体中的ICollection(实体框架6,ASP.NET核心)

时间:2016-10-05 23:27:55

标签: c# asp.net entity-framework

我有两种模式:

public class Customer : People
  {
     public int CustomerID { get; set; }
     public decimal? Weight { get; set; }
     public decimal? Height { get; set; }
     public ICollection<Purchase> Cart { get; set; } 
  }

public class Purchase
  {
     public int PurchaseID { get; set; }
     public DateTime Time { get; set; }
     public decimal TotalPrice { get; set; }
     public int Amount { get; set; }
     public Good Good { get; set; }
   }

我已经有了一个客户,需要更新他的购物车(例如为其添加smth)。

我试图像这样做,但这什么都不做。我做错了什么?

Customer customer = new Customer()
      {
        CustomerID = currentID.Value                   
      };
var cart = new List<Purchase>();
      cart.Add(new Purchase()
      {
        Amount = 1,
        Good = good,
        Time = DateTime.Now,
        TotalPrice = good.Price    
      });                                                                                
      customer.Cart = cart;
      var entry = _context.Entry(customer);
      _context.Update(customer);
      _context.SaveChanges();

更新:

我试图做一些建议的事情,但是......我生活中无法理解的是什么? Context when i try to updateContext when i try to view updated Customer

1 个答案:

答案 0 :(得分:0)

当您尝试更新实体时。所以这就是我的追随和运作方式。

 context.Entry(customer).State = System.Data.EntityState.Modified;
 context.ChangeTracker.DetectChanges();
 context.SaveChanges();