arch / UnitOfWork

A plugin for Microsoft.EntityFrameworkCore to support repository, unit of work patterns, multiple database with distributed transaction supported, and MySQL multiple databases/tables sharding supported.
MIT License
1.34k stars 343 forks source link

Entity Inserted and updated in one session, throws error #114

Open sudipp opened 5 years ago

sudipp commented 5 years ago

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);
    }
liuhll commented 3 years ago

me to