繁体   English   中英

ObjectStateManager中已存在具有相同键的对象。 使用AsNoTracking时

[英]An object with the same key already exists in the ObjectStateManager. when using AsNoTracking

SO中有很多错误,但我认为这种情况有所不同。

我有一些工作正常的代码,我更新一个实体,等等。但问题是它被缓存,当我使用AsNoTracking()禁用缓存时,它开始抛出此异常;

我做了以下几点:1。在页面中,我获得了EcoBonusRequest。 2.用户单击一个按钮,它会修改currentstatus proeprty,并将一个列表项添加到工作流历史的集合中(ecobonusrequestobject的相关集合)。 3.我调用udpate方法,将状态设置为modified,这里抛出了异常。

这是我的代码>

EcoBonusRequestRepository.cs

public void UpdateEcoBonusRequest(EcoBonusRequest ecoBonusRequest)
            {
                _context.EcoBonusRequests.Attach(ecoBonusRequest);
                _context.Entry(ecoBonusRequest).State = EntityState.Modified;
            }

EcoBonusRequestBL

public void Update(EcoBonusRequest ecoBonusRequest)
        {
            DALFacade.UpdateEcoBonusRequest(ecoBonusRequest);
        }

EcoBonusRequest

public void ChangeStatus(EcoBonusRequest ecoBonusRequest, string stepname, string who, string choosenoption)
        {

            ecoBonusRequest.WorkflowHistories = new List<WorkflowHistory>
                                                   {
                                                       new WorkflowHistory()
                                                           {
                                                               Date = DateTime.Now,
                                                               What = choosenoption,
                                                               StepName = stepname,
                                                               Who = who
                                                           }
                                                   };

            ecoBonusRequest.CurrentStatus = _currentStepBlo.StepName;
            var ecoBonusRequestBL = new EcoBonusRequestBL();
            ecoBonusRequestBL.Update(ecoBonusRequest);
        }

这是我首先获得对象的方式:(我不会在这里粘贴所有图层的所有代码)

protected override void OnInit(EventArgs e)
        {
            var requestBaseId = RequestBaseId;
            if (requestBaseId != null)
            {
                EcoBonusRequest request = GetDBRequest(requestBaseId.Value);

在达尔

public IQueryable<EcoBonusRequest> FindEcoBonusRequests(System.Linq.Expressions.Expression<Func<EcoBonusRequest, bool>> predicate)
            {
                return _context.EcoBonusRequests.AsNoTracking().Where(predicate);
            }

是的,这是一个有趣的问题,这里的问题来自于试图重新附加已经附加到上下文的实体。 这可能来自逻辑错误,或者您可能在不清除附加对象的情况下重用上下文。 数据库上有一个本地集合,您可以使用它来查看当前附加到上下文的项目。

ctx.YourEntityCollection.Local

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM