2016-10-05 173 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