Reputation: 12874
I use EF 6.1 alpha with Caliburn.Micro 2.0 -alpha2.
I have a ViewModel called ProductWorkspaceViewModel, which contains a ProductViewModel. Both of these ViewModels using EF with respective Context, while the first read all Products from Db and shows them in a list and the later do CRUD operation on the selected item.
Now, when I delete, add, or update the Product from ProductViewModel, it should get updated in the ProductWorkSpaceViewModel. I update the Workspace with EventAggregator and either use LoadAll() or Send the update ProductEntity to the WorkSpaceViewModel. But when I select the same updated Product from Workspace, the Related Properties which are Lazy are not updated in ProductViewModel, because both have a different instance of Context.
I am think of using a shared Context for both of these ViewModel, but have read on other questions, like Context should not be shared and should be disposed soon after operation completed like delete.
How can I best achieve the solution for above problem. Also the Workspace Context is used by many DataTemplates.
Should I use a shared Context or I should update either ViewModel with all Lazy Properties loaded. But that will add more code and is complex.
Looking for a Best Practise.
Upate: I just mentioned DbContext for reference, I use a DAL which has a class that Inherits from DbContext.
Also I want to update that my Main project doesn't use either EF or any DAL. It acts as a host to all modules that I have created as Sub Project. For eg., ProductViewModel is part of Inventory Module, which I load into Main.exe using IoC (MEF)
Upvotes: 2
Views: 590
Reputation: 12119
The best practice is for your ViewModel
s not to use the Entity Framework or it's DataContext
s directly but to have a Data Access Layer which takes care of all the DB operations instead and Your VMs should use a Service Provider to communicate with your DAL.
As a matter of fact you shouldn't even have a reference to Entity Framework in your main project but in your DAL Class Library only
In your VMs you should use an ObservableCollection
of Product
classes and both your VMs should work with that same ObservableCollection
in a Parent-Child mode in which case any changes you make to a Product
in your ProductViewModel
will immediately affect your ProductWorkspaceViewModel
.
Upvotes: 4