UnitOfWork icon indicating copy to clipboard operation
UnitOfWork copied to clipboard

Entity Inserted and updated in one session, throws error

Open sudipp opened this issue 6 years ago • 1 comments

I have a situation, where I insert an entity, and then update it on the same session context. I get following error, after calling repo.Update(jobExecution);

please help.

{System.InvalidOperationException: The instance of entity type 'JobExecution' cannot be tracked because another instance with the same key value for {'JobExecutionSk'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

private readonly IUnitOfWork _UOW;
    public JobsController(IUnitOfWork uow)
    {
        _UOW = uow;
    }
	
    public async Task test()
    {
        var jobName = "test";
        var _repoJobExecution = _UOW.GetRepository<JobExecution>();
        var _repoJob = _UOW.GetRepository<Entities.Models.Job>();
        var jobExecution = new JobExecution
        {
            JobSk = 1,
            JobStatus = JobStatus.InProgress,
        };

        _repoJobExecution.Insert(jobExecution);
        await _UOW.SaveChangesAsync().ConfigureAwait(false);

        jobExecution = await _repoJobExecution.GetFirstOrDefaultAsync(
                predicate: j => j.Job.JobName.Equals(jobName)
                    && j.JobStatus == JobStatus.InProgress).ConfigureAwait(false);

        jobExecution.JobStatus = JobStatus.Completed;
        jobExecution.EndDatetime = DateTime.Now;
        _repoJobExecution.Update(jobExecution); //error thrown in this line
        await _UOW.SaveChangesAsync().ConfigureAwait(false);
    }

sudipp avatar Sep 12 '19 17:09 sudipp

me to

liuhll avatar Apr 02 '21 19:04 liuhll