Entity Framework Core Tutorial 實體已斷開連接
介紹
DbContext實例自動跟踪從數據庫返回的實體,並且在調用SaveChanges時會檢測對這些實體所做的任何更改,並且還會根據需要更新數據庫。
- 有時使用一個上下文實例查詢實體,然後使用其他實例進行保存。
- 在這種情況下,第二個上下文實例需要知道實體是新的(應該插入)還是現有的(應該更新)。
識別新的或現有的實體
有必要確定是否插入或更新實體。自動生成的密鑰的值通常可用於確定是否需要插入或更新實體。
- 如果尚未設置密鑰,則該實體必須是新的並且需要插入。
- 另一方面,如果已設置鍵值,則它必須先前已保存,現在需要更新。
using (var context = new MyContext()) { if (customer.CustomerId == 0) { context.Customers.Add(customer); } else { context.Customers.Update(customer); } context.SaveChanges(); }
您可以使用內置方法為任何實體類型和密鑰類型執行此操作。
using (var context = new MyContext()) { if (!context.Entry(customer).IsKeySet) { context.Customers.Add(customer); } else { context.Customers.Update(customer); } context.SaveChanges(); }
如果未自動生成鍵值,則可以使用Find()
方法查詢實體。
using (var context = new MyContext()) { var existingCustomer = context.Customers.Find(customer.CustomerId); if (existingCustomer == null) { context.Add(customer); } else { context.Entry(existingCustomer).CurrentValues.SetValues(customer); } context.SaveChanges(); }