简体   繁体   English

Linq DataContext最佳实践

[英]Linq DataContext best practice

What is the best way (practice) to deal with a Linq Database DataContext in C# WPF. 在C#WPF中处理Linq Database DataContext的最佳方法(实践)是什么? Use a global application wide DataContext which is shared in every viewModel or to open for every transaction a own DataContext? 使用全局应用程序范围的DataContext,它在每个viewModel中共享,或者为每个事务打开一个自己的DataContext?

Based on information on msdn and StackOverflow it is recommended to create a new DataContext for every transaction. 根据msdnStackOverflow的信息,建议为每个事务创建一个新的DataContext。 But in my case I would like to lookup data in one viewmodel and passing them to another viewmodel to alter values. 但在我的情况下,我想在一个viewmodel中查找数据并将它们传递给另一个viewmodel来改变值。 Creating a new DataContext in the altering viewmodel results in mismatching object states. 在更改viewmodel中创建新的DataContext会导致对象状态不匹配。 (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 (第一个viewModel中的选定对象不存在于第二个viewModel的DataContext中,因为该对象绑定到较旧的DataContext)序列图以便更好地理解

在此输入图像描述

The "EditViewModel" is not able to edit the passed value with the new DataContext, because the object is related to the "LookupViewModel's" DataContext. “EditViewModel”无法使用新的DataContext编辑传递的值,因为该对象与“LookupViewModel”的DataContext相关。

I thought about passing the DataContext as well. 我也考虑过传递DataContext。 But since the LookupViewModel has no time limitation when its going to call an editViewModel, the DataContext could get out of date. 但是由于LookupViewModel在调用editViewModel时没有时间限制,因此DataContext可能会过时。 (And a refresh would be essential). (刷新是必不可少的)。 Furthermore, sometimes I pass from different viewModels from different DataContexts values to one editViewModel. 此外,有时我从不同的viewModel传递不同的DataContexts值到一个editViewModel。

How am I able to tread objects from a DataContext in another DataContext without receiving any exceptions? 如何在没有收到任何异常的情况下从另一个DataContext中的DataContext中处理对象? 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. 你的ViewModel不应该知道DataContext,它们的细节太低了。

And they most definitely shouldn't create them! 他们绝对不应该创造它们! - so the first thing you should do is look into Ioc\\DI pattern. - 所以你应该做的第一件事就是研究Ioc \\ DI模式。

Furthermore, you should add additional layer (usually called DAL) to abstract this low level details of managing the DB state. 此外,您应该添加额外的层(通常称为DAL)来抽象管理DB状态的这种低级细节。

also, if your app is big, consider the Repository with UnitOfWork pattern. 此外,如果您的应用程序很大,请考虑具有UnitOfWork模式的存储库。

So, to conclude: you should look into this three OO patterns: 因此,总结一下:你应该研究这三个OO模式:

  1. Dependency injection 依赖注入

  2. DAL DAL

  3. Repository (and maybe UnitOfWork) 存储库(也许是UnitOfWork)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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