简体   繁体   中英

Linq DataContext best practice

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

在此输入图像描述

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM