Skip to main content
 首页 » 编程设计

c#之Sys.WebForms.PageRequestManagerServerErrorException : An entity object cannot be referenced by multiple instances of IEntityChangeTracker

2024年01月01日55pengyingh

故事:

当我尝试保存一些东西时出现了一个奇怪的错误,我收到了这条错误消息

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

我真的不知道那是什么以及为什么会出现,只有当我尝试保存我的插入和更新正在工作的东西时,它才会出现,只有当我尝试从我的 Telerik 网格中保存一些东西到数据库中时才会出现

    if (this.annualVacationList != null) 
        { 
            List<AnnualVacation> vacationToSave = this.annualVacationList; 
            IEnumerable<AnnualVacation> existing = paramUser.AnnualVacations; 
            foreach (AnnualVacation toSave in vacationToSave) 
            { 
                AnnualVacation existingItem = existing.Where(x => x.AnnualVacationId == toSave.AnnualVacationId).SingleOrDefault(); 
                if (existingItem == null) 
                { 
                    ctx.AddToAnnualVacations(toSave); 
                } 
                else 
                { 
                    existingItem.FromDate = toSave.FromDate; 
                    existingItem.ToDate = toSave.ToDate; 
                    existingItem.WorkingTime = toSave.WorkingTime; 
                    existingItem.VacationDays = toSave.VacationDays; 
                } 
            } 
        } 
        ctx.SaveChanges(); 
    } 

调试后,我发现 Project.Name.Designer.cs 中的代码失效了 ..... 哦哦

  public void AddToAnnualVacations(AnnualVacation annualVacation) 
    { 
        base.AddObject("AnnualVacations", annualVacation); 
    } 

请您参考如下方法:

嘿嘿

我以某种方式自己得到它, View 状态没有分离上下文,这就是我刚刚创建的问题

var tmp = new AnnualVacation 
                    { 
                        FromDate = toSave.FromDate, 
                        ToDate = toSave.ToDate, 
                        WorkingTime = toSave.WorkingTime, 
                        VacationDays = toSave.VacationDays, 
                        UserId = toSave.UserId 
                    }; 

在上面的同一个 if 查询中 (if(existing Item==null)) 并且它有效 但仍然感谢所有试图帮助我的人^^