EntityFramework - Use Entities in Modules without access to the Database
I'm currently creating an application which is highly modular (using the Prism-Framework) and accesses a database via the EntityFramework implemented in CodeFirst.
My goal is to seperate the actual writing of the data into the Database from the "normal" use of the created Entities. Writing to the Database shall only be done by the main-Application but the Modules should still be able to use the Entity-Classes.
Thus, they must know the DataContext or at least the Entiy Classes. Here is the problem, though: If a module changes a property of an Entity Class and the main-Application calls "SaveChanges()" on the DataContext for some other reason, the changes made by the module are automatically saved to the Database without the main-Application having control over it.
How can I prevent this behaviour? The Modules must not be able to change the Database-Content, except via a defined Interface to the main-Application.
My first thought was to implement ICloneable in every entity-Class and to only pass clones of the Entity-Objects to the Modules to work with. The modules would then, if they wanted to request a change in the database, pass the cloned Objects to the main-Application which updates the original object and calls "SaveChanges()" on the DataContext.
Do you guys think this is a viable solution, or might there be a better way to implement this behaviour?
Thanks in advance!
Use the DbSet.AsNoTracking() Method to enable reading data from the database that will not be tracked by the DbContext.