1
我有我的數據庫上下文:ASP.NET MVC 3數據庫上下文查詢
public class ProductContext : DbContext
{
public ProductContext() : base ("DefaultConnection") {}
public DbSet<Product> Products {get;set;}
}
和我的倉庫:
public class ProductRepository : IProductRepository
{
private ProductContext _dbContext = new ProductContext();
public IQueryable<Product> Products { get { return _dbContext.Products; } }
}
當我查詢我的Edit
Action
數據庫:
public ActionResult Edit(Guid id)
{
var item = _repository.Products.FirstOrDefault(x => x.Id.Equals(id));
return View(item);
}
我通常會用一個ViewModel
但這純粹是爲了展示場景。
當我使用var item
行查詢數據庫時,EntityFramework
是否更改item
的狀態。
我可以傳遞item
各地通過Services
在Service Layer
衆多,最後用我的方法保存:
public void SaveEntity<TEntity>(TEntity entityToSave) where TEntity : DbEntity
{
if (entityToSave.Id.Equals(Guid.Empty))
_dbContext.Set<TEntity>().Add(entityToSave);
else
_dbContext.Entry<TEntity>(entityToSave).State = EntityState.Modified;
_dbContext.SaveChanges();
}
它不會拋出一個異常說,已經有一個Entity
與與您試圖保存的那個相同Id
?
EF將嘗試再次插入該類別,因爲它很可能會附加到您的'DbContext'的另一個實例。 EF無法知道該類別已存在,所以它會嘗試插入它,從而導致重複的鍵錯誤。這個問題可以通過在整個請求中使用'DbContext'的相同實例來解決。如上所述填寫外鍵字段將工作得很好。 –
是的,我認爲這是問題,但我注入這將使用'DbContext'的一個實例庫,我走動的地方實體,所以它只是更容易使用'Id'領域。 –
確保您爲請求的範圍創建實例。 –