There are many errors here in SO, but this scenario I think its different.
I had some code that was working fine, I update one entity, etc. But the problem is that it was being cached, when I disabled caching with AsNoTracking(), then it started to throw this exception;
What I do its the following:
1. In the page I get a EcoBonusRequest.
2. The user clicks a button and it modifies the currentstatus proeprty, and it addsa a list item to a collection of workflowhistories, (an associated collection of the ecobonusrequestobject).
3. I call the udpate method, setting state to modified, here it throwed the exception.
Here is my code>
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 Page
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);
}
This is how I get the object first: (I am not going to paste all code from all layers here)
protected override void OnInit(EventArgs e)
{
var requestBaseId = RequestBaseId;
if (requestBaseId != null)
{
EcoBonusRequest request = GetDBRequest(requestBaseId.Value);
In the dal
public IQueryable<EcoBonusRequest> FindEcoBonusRequests(System.Linq.Expressions.Expression<Func<EcoBonusRequest, bool>> predicate)
{
return _context.EcoBonusRequests.AsNoTracking().Where(predicate);
}
Yeah this is a fun one, the issue here comes from trying to re-attach an entity which is already attached to the context. This can come from a logic error or perhaps you are reusing your context without clearing the attached objects. There is a local collection on the database which you can use to see what items are currently attached to the context.