0

我正在使用 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 实例引用

这很奇怪,因为我没有其他参考(如您所见,上下文是新启动的)。我怎样才能摆脱这个?

4

2 回答 2

2

您的错误可能来自 PaymentToken 实体。

您有一个要附加到adventureBooking. 很可能,您使用相同的逻辑通过不同的通用存储库获取该实体 - 您在该存储库中创建了一个上下文并检索了该项目。由于令牌实体附加到您的TokenRepository,并且您的adventureBooking实体附加到您的,因此comBookingRepository您有 2 个不同的上下文。要么断开你的token实体与其原始存储库的连接,要么重载你的存储库以便能够传递你的上下文,这样你的上下文就会在你的存储库之间共享。

 public GenericRepository(DbContext context)
        {
            Context = context;
            DbSet = Context.Set<TEntity>();
        }

然后在您的代码中创建您的存储库:

var context = new new ComTrContext();
var  ComBookingRespository = new ComBookingRespository(context );
var  tokenRepository = new tokenRepository (context );
于 2013-02-23T01:35:12.253 回答
0

您的上下文的另一个实例是跟踪相关实体。

于 2013-02-23T01:32:03.033 回答