mehdime / DbContextScope

A simple and flexible way to manage your Entity Framework DbContext instances
http://mehdi.me/ambient-dbcontext-in-ef6/
MIT License
634 stars 271 forks source link

Synchronizing Model State to Database #18

Open ChrisMarinos opened 9 years ago

ChrisMarinos commented 9 years ago

Hi, this is more of a question than an issue, but this seems to be the best place to post. Feel free to close/move elsewhere if needed.

I'm wondering how you handle cases where EF's model state becomes out of sync with the database's state. Consider a basic user permissions structure where a user can have many roles, and roles have many permissions. Let's say you have a service that adds a permission to a role, and a service that removes a permission from a role. Now let's say that you want to determine what users will have their permissions changed by the addition or removal of a permission to a role. There are too many users to load them all into memory for the role in question, so you have to perform a database query to determine what users will be impacted, then do the update. However, what happens if the service is called from another service that also changed role permissions? Now you have pending database changes that will cause your query to return invalid results. With a normal dbcontext, you can just save to sync EF's model state to the database. However, with dbContextScope, you don't know if and when your changes will be synced since you could always be in a nested scope.

This example may be a little contrived for the purposes of forming a question, but I'm curious to hear how others are dealing with query, update, re-query workflows. For now, our team is changing our save behavior to be eager instead of lazy. We're also creating a transaction with the parent dbcontextscope and committing the transaction when the parent scope is saved. This gives us the rollback behavior of normal DbContextScope with the control of allowing our models to be kept in sync.