2016-10-05 151 views
0

我有两个型号:更新的ICollection在实体(实体框架6,ASP.NET核心)

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(); 

UPDATE:

我试图做的事情建议,但..我不明白,对我的人生? Context when i try to updateContext when i try to view updated Customer

+0

var entry = _context.Entry(customer);'只是为了好奇心,你在哪里使用入口变量? –

+0

我试着按照[本指南](http://stackoverflow.com/a/15339512/5380012),但在entry.Property(e => e.Cart).IsModified = true;这就是为什么我删除了这一行,并忘记添加到问题 – Sergey

回答

0

正如您试图更新您的实体。所以这是我如何遵循和它的作品。

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

谢谢,但它似乎不工作。我认为问题是我尝试写一个集合 – Sergey