我正在使用 EF 5.0 并且有一个通用的上下文:
namespace ComTr.Web.BusinessLayer
{
public class GenericRepository<TEntity> : IDisposable where TEntity : ComTrBaseEntity //Use as base class to allow access to base entities properties like modified
{
internal ComTrContext Context;
internal DbSet<TEntity> DbSet;
public GenericRepository()
{
Context = new ComTrContext();
DbSet = Context.Set<TEntity>();
}
public virtual TEntity GetById(object id)
{
return DbSet.Find(id);
}
/// <summary>
/// Edits the specified entity to update. Will attach entity to the context
/// </summary>
/// <param name="entityToUpdate">The entity to update.</param>
/// <returns></returns>
public virtual TEntity Edit(TEntity entityToUpdate)
{
entityToUpdate.Modified = DateTime.Now;
DbSet.Attach(entityToUpdate);
Context.Entry(entityToUpdate).State = EntityState.Modified;
return entityToUpdate;
}
}
}
现在我尝试使用以下代码更新单个值:
var ComBookingRespository = new ComBookingRespository();
comBooking= ComBookingRespository.GetById(adventureBookingId);
////Save Token in database
comBooking.PaymentToken = token;
ComBookingRespository.Edit(comBooking);
VS 将在以下行停止:
Context.Entry(entityToUpdate).State = EntityState.Modified;
带有以下错误消息:
一个实体对象不能被多个 IEntityChangeTracker 实例引用
这很奇怪,因为我没有其他参考(如您所见,上下文是新启动的)。我怎样才能摆脱这个?