Skip to content

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

Open
@sudipp

Description

@sudipp

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);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions