[英]Adding record with related child object in Entity Framework using Repository Pattern
我無法將實體添加到包含與現有對象的關系的數據庫中。 我搜索了很多,找不到合適的解決方案。 我將盡可能簡單地描述這一點。
public class Store : IEntity
{
public int StoreId { get; set; }
public string StoreName { get; set; }
public virtual Address Address { get; set; }
public virtual Contractor Contractor { get; set; }
}
public class Product : IEntity
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public virtual Store Store { get; set; }
}
在存儲庫中,我添加了這樣的記錄。 這是泛型類
public TEntity Add(TEntity entity)
{
using (var context = new TContext())
{
var addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
context.SaveChanges();
return entity;
}
}
現在當我嘗試像這樣添加新記錄時
var store = storeManager.GetBy(x => x.StoreId == 1);
var product = new Product() { ProductName = "Bananas", Store = store };
productManager.Add(product);
productManager.GetAll().ForEach(x => Console.WriteLine(x.ProductName + " " + x.Store.StoreId));
商店關系被添加為新商店並獲得新的 ID。 有人知道我該如何解決這個問題嗎?
來自數據庫的示例:
StoreId StoreName Address_AddressId Contractor_ContractorId
1 NULL 1 1
2 NULL 2 2
3 NULL 3 3
4 NULL 4 4
5 NULL 5 5
6 NULL 6 6
7 NULL 7 7
這是我關於stackoverflow的第一個問題。
問題的最可能原因是您正在為插入操作創建上下文的新實例。 正因為如此,這個新上下文不僅獲得了一個新產品,而且還獲得了一個從另一個上下文接收的商店,但是這個新創建的上下文不知道商店已經在數據庫中了。
一個普遍的問題是不正確地管理數據庫上下文的生命周期。 EF 實例與用於接收它們的上下文相關聯,您不能只是將一個實體從一個上下文放入另一個上下文。
您應該在多個管理器之間共享數據庫上下文的實例,而不是在每個管理器操作中創建新上下文。
public class StoreManager
{
public StoreManager( Context context )
{
this.context = context;
}
public TEntity Add(TEntity entity)
{
var addedEntity = context.Entry(entity);
addedEntity.State = EntityState.Added;
context.SaveChanges();
return entity;
}
}
編排必須首先創建上下文並確保它在兩個管理器之間共享
var context = new DbContext();
var storeManager = new StoreManager( context );
var productManager = new ProductManager( context );
var store = storeManager.GetBy(x => x.StoreId == 1);
var product = new Product() { ProductName = "Bananas", Store = store };
productManager.Add(product);
productManager.GetAll().ForEach(x => Console.WriteLine(x.ProductName + " " +
x.Store.StoreId));
通常,所有這些都是在單個作用域中創建的,例如在請求作用域中,因此單個 Web 請求具有單個數據庫上下文,並且每個存儲庫都獲得完全相同的上下文實例。
您也可以按照官方教程進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.