0
我有一個通用的存儲庫,使用實體框架4與DbContext api。當調用Update時,存儲庫將使用工作單元對象註冊實體和存儲庫。實體框架代理破壞存儲庫類
當在工作單元上調用提交時,更新的實體正在被EF跟蹤(通常不是,因爲存儲庫用於ASP MVC及其模型綁定技術),該類型是代理類型,而由於類型不存在於模型中,因此引發異常。 PersistUpdateOf然後在EF跟蹤實體時落下,因爲EF使用代理類。附圖顯示了這一點。
是否有一項解決方案,不涉及禁用將與跟蹤或未跟蹤的實體一起工作的代理。
public void Update<TEntity>(TEntity entity) where TEntity : EntityBase
{
//Audit the update
if (entity is IAuditable)
{
(entity as IAuditable).AuditEntityUpdate();
}
//Register the entity as Amended with the unit of work
_unitOfWork.RegisterAmended(entity, this);
}
public virtual void PersistUpdateOf(EntityBase entity)
{
_context.Set(entity.GetType()).Attach(entity);
_context.Entry(entity).State = EntityState.Modified;
}
順利!我從Microsoft的實體框架教程中得到了那個似乎什麼也不做的Attach代碼:( – Lee
刪除操作:_context.Set(entity.GetType())。Remove(entity);具有相同的問題。將其EntityState設置爲刪除/刪除? – Lee
@lee是。您可以在庫中使用'_context.Set(typeof(TEntity))'而不是'_context.Set(entity.GetType())'。 – Eranga