为什么我会获得IEntityChangeTracker的多个实例?

时间:2014-07-06 13:07:15

标签: c# entity-framework asp.net-mvc-5 entity-framework-6

我收到以下错误:

  

类型' System.InvalidOperationException'的例外情况发生在   EntityFramework.dll但未在用户代码中处理

     

附加信息:无法引用实体对象   IEntityChangeTracker的多个实例。

运行时:

public bool AddUser(string username, string clanName) {

            if (userRankValid(clanName))
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser recruit = userManager.FindByNameAsync(username).Result;
                Clan clan = uow.ClansRepository.Get(u => u.Name == clanName).FirstOrDefault();

                if (clan != null && recruit != null)
                {
                    var ctum = uow.ClanToUserRepository.Get(u => u.User.UserName == username).Where(u=>u.Clan.Name == clanName).FirstOrDefault();
                    if(ctum == null)
                    {
                        ClanToUserMap recMap = new ClanToUserMap();
                        recMap.Clan = clan;
                        recMap.User = recruit;
                        recMap.Rank = "Private";
                        recMap.User = recruit;
                       //clan.Members.Add(recMap);
                      //  recruit.Clans.Add(recMap);
                        uow.ClanToUserRepository.Insert(recMap);
                        uow.Save();
                        return true;
                    } 
                }
            }
            return false;
        }

现在,我意识到这一定是因为有多个上下文实例。我不明白的是为什么有......所有的电话都是最后一次插入。但我正在我的通用存储库中实现.AsNoTracking()以进行任何GET调用,所以我不明白为什么上下文会混淆:

public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter).AsNoTracking();
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty).AsNoTracking();
            }

            if (orderBy != null)
            {
                return orderBy(query).AsNoTracking().ToList();
            }
            else
            {
                return query.AsNoTracking().ToList();
            }
        }

INSERT上发生错误

0 个答案:

没有答案