Question

I often have the situation that I need to pass a linq2sql object from one WPF window to another one.

For example I have a window with a list of linq2SQL objects. The list is bound from a public declared DataContext in the "Window_Loaded"-event. With a double click on one of these items a second window opens and the object can be edited. While opening the selected object is passed to a property of the second window. After the user has made some changes he decides to discard the changes and closes the second window.

Now because the input fields are bound directly to the Linq2SQL object the changed values are still present.

What is the best practice in this situation? Is it better to pass a newly created object from a new created DataContext to the second window? Then I have to somehow refresh the list on the first window when the changes are wanted.

Or can I use the already bound object from the list of objects from the first window and pass it directly to the second window?

I know that I can refresh the object when I have to reload the object

DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, MyObject);

What is the best practice?

Was it helpful?

Solution

The question is more general and touches the important issue: what lifetime policy best suits the linq2sql datacontext in different types of applications.

In case of a web application, this question has a simple answer: the "per-httprequest" lifetime policy is the most convenient.

In your case, a WPF application, there are two approaches I am aware of:

  1. in a "per-the-lifetime-of-the-application" policy you would create a single data context for the lifetime of your application. Although technically this works, there are potential issues with the memory consumption - as the application retrieves more and more data, the first level cache in the data context grows without control and could possibly just run out of resources at some point

  2. in a "per-presenter (view)" policy you create a new data context in each of your presenter (view model) (or view, if you don't follow mvvm) which means that two different views do not share the same context. I'd say this is recommended approach, there are no risks of unwanted resource issues, however, you need an additional mechanism to pass events between views so that views could be refreshed when the data changes.

Note, that all your business logic should be unaware of the actual policy. To do so, let your data context be injected (by constructor for example) to any class that uses it. Depending on the actual policy, a proper context is injected into a business class. This way, you could even change the lifetime management policy someday with no need to refactor your business code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top