简体   繁体   中英

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

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

在此处输入图片说明

在此处输入图片说明

UpdateAsync service:

在此处输入图片说明

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.

在此处输入图片说明

在此处输入图片说明

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM