4

What is the best way (practice) to deal with a Linq Database DataContext in C# WPF. Use a global application wide DataContext which is shared in every viewModel or to open for every transaction a own DataContext?

Based on information on msdn and StackOverflow it is recommended to create a new DataContext for every transaction. But in my case I would like to lookup data in one viewmodel and passing them to another viewmodel to alter values. Creating a new DataContext in the altering viewmodel results in mismatching object states. (The selected object in the first viewModel does not exist in the DataContext of the second viewModel, since the object is bound to the older DataContext) Sequence diagram for better understanding

enter image description here

The "EditViewModel" is not able to edit the passed value with the new DataContext, because the object is related to the "LookupViewModel's" DataContext.

I thought about passing the DataContext as well. But since the LookupViewModel has no time limitation when its going to call an editViewModel, the DataContext could get out of date. (And a refresh would be essential). Furthermore, sometimes I pass from different viewModels from different DataContexts values to one editViewModel.

How am I able to tread objects from a DataContext in another DataContext without receiving any exceptions? Or shouldn't I completely reconsider the whole application design?

1
  • 1
    There is a nice blog about DataContext scope that goes into some solutions. It is for Entity Framework, but same should apply to linq mehdi.me/ambient-dbcontext-in-ef6
    – Mats391
    Dec 1, 2016 at 10:21

1 Answer 1

1

Your ViewModels shouldn't know about DataContext,it's too low-level detail for them.

And they most definitely shouldn't create them! - so the first thing you should do is look into Ioc\DI pattern.

Furthermore, you should add additional layer (usually called DAL) to abstract this low level details of managing the DB state.

also, if your app is big, consider the Repository with UnitOfWork pattern.

So, to conclude: you should look into this three OO patterns:

  1. Dependency injection

  2. DAL

  3. Repository (and maybe UnitOfWork)

1
  • Thanks for those keywords. Going to take a deep look at those.
    – Bin4ry
    Dec 1, 2016 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.