Updates I made within the background worker do not appear in the database

254 Views Asked by At

I have two entities in the project as follows and I can update these entities within a service.

enter image description here

enter image description here

UpdateAsync service:

enter image description here

UpdateAsync method works as expected.

However, although I wrote similar codes, the change I made in the background worker only affects Monitoring. In short, the MonitoringStep entity is not updated in the background worker.

Below you can see the codes of the method I created for the background worker:

        var monitorRepository = workerContext.ServiceProvider.GetService<IMonitorRepository>();

        var monitor = await monitorRepository.GetAsync(Guid.Parse("E3076832-D653-79BC-002B-39F8403C4EB0"));

        monitor.SetName("stackoverflow-example");
        monitor.MonitorStep.Url = "http://stackoverflow.com/";
        
        await monitorRepository.UpdateAsync(monitor, true);

As a result, the Name property in the Monitor table is updated, but the Url in the MonitorStep table is not updated.

Below you can see the exception that occurred during saving and the content of my entity.

enter image description here

enter image description here

I think there is something I'm missing, can you help me?

2

There are 2 best solutions below

2
On BEST ANSWER

From what I could understand from your code in here and according to the documentation and this website there are two issues, one; a property is missing in the MonitorStep class:

    public Monitor Monitor { get; set; }

Second, since you are mapping a one-to-one relationship, your mapping is missing the reference to the one-to-one table/class (Monitor):

b.HasOne(n => n.MonitorStep).WithOne(m => m.Monitor).HasForeignKey<MonitorStep>(x => x.MonitorId).IsRequired();
0
On

I found the problem. In fact, the problem is in the DbContext.Attach(entity); line in the UpdateAsync method. This line did not save changes until Save Changes was done. I was doing AutoSave, actually, I expected that part to work properly but it didn't work. After a long effort, I was able to create a UnitOfWork and save the changes thanks to it. Thank you for your answers.