刚用EF4.1的时候在MSDN上接触了通用的Update()方法。如:
public virtual void Update(TEntity entityToUpdate)
{
if (context.Entry(entityToUpdate).State == EntityState.Detached)
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
但是看到网上看到有改进的Update()方法,但不知道为什么要把这个方法进行改进?
具体做法是:项目中引用EmitMapper.dll。
修改Update()中的方法:
public virtual void Update(TEntity entityToUpdate)
{
var entry = context.Entry(entityToUpdate);
if (entry.State == EntityState.Detached)
{
var entityOrigin = GetByID(entityToUpdate.ID);
EmitMapper.ObjectMapperManager
.DefaultInstance.GetMapper<TEntity, TEntity>()
.Map(entityToUpdate, entityOrigin);
}
}
EmitMapper主要用于复制复杂类型的对象。但是为什么要用这种方法改进Update()方法。还得继续研究下。在网上http://q.cnblogs.com/q/29940/ 看到一个EF结合WCF使用碰到通用Upate()方法问题,说不可能Attach到。他是这样修改Update方法的:
public
virtual
void Update(T entity)
{
T current = this.Where(m => m.Id.Equals(entity.Id))
.SingleOrDefault();
if (current != null)
{
var context = ((IObjectContextAdapter)DbContext).ObjectContext;
ObjectStateEntry objectStateEntry;
if (context.ObjectStateManager.TryGetObjectStateEntry(current, out objectStateEntry))
{
objectStateEntry.ApplyCurrentValues(entity);
objectStateEntry.SetModified();
this.Commit();
}
}
}