How to save related data from another DbContext in EF Core?

.net-core asp.net-core ef-core-2.1 entity-framework-core

Question

I have been trying to build a CMS using .NET Core 2.1 with a feature to stage web content changes, therefore I have three sites in my system architecture:

  1. CMS Site - User could propose changes to web content through the CMS, and the changes will be pushed to the Staging/Production Site after being approved by admin.
  2. Staging Frontend - The frontend web for internal UAT purposes, displays all approved/unapproved web content.
  3. Production Frontend - The frontend web facing the public, displays only approved web content.

I have three DbContext instances injected for achieving the above:

  1. CmsContext - Stores first-round web content changes proposed by a user.
  2. StagingContext - Where the staging web frontend reads web content
  3. ProductionContext - Where the production web frontend reads web content

The problem I encountered was, when I try to do the following (with lazy-loading enabled):

var entity = await stagingContext.FindAsync(entityType, entityId);
productionContext.Update(entity);
await productionContext.SaveChangesAsync();

navigation properties are not updated as what I have expected.

I have also tried the ChangeTracker.TrachGraph approach, but it does not iterate through navigation properties.

I understand that the reason might be, even though lazy-loading is enabled, the navigation properties are never accessed before, so they are not filled up with values for productionContext to update.

I have read through the Microsoft Docs before I post this question, but could not figure out the correct way to do this. May I have your kind help on this guys? thanks

1
2
10/15/2018 5:33:10 AM

Accepted Answer

You say that you use lazy loading but properties are never accessed before, so I think you have to eager load them with Include.

You have to replace FindAsync call with Include to eager load all navigation properties you need, and then use SingleOrDefaultAsync or SingleAsync. Because properties are lazily loaded, they never get loaded because you never access them and EF Core has nothing to track when you call productionContext.Update(entity);

I don't think calling Update accesses any properties for lazy loading to work, it just sets EntityState. I'm not sure if call to SaveChangesAsync change that. But if it doesn't work then it's possible that it's not lazily loaded.

If you just want to eager load everything you can take a look at Entity Framework Core 2.0.1 Eager Loading on all nested related entities

0
10/15/2018 12:07:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow