Linq和DataContext [英] Linq and DataContext

查看:120
本文介绍了Linq和DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个应用程序只有一个DataContext并通过单例共享它是否可以?

Would it be ok to have only one DataContext per app and share that through an singleton?

之所以这样问,是因为我想以每种形式使用DataContext,但是我意识到,如果我在一个DataContext中更改了一些实体,那么如果以前使用过,我会对其进行刷新.

I ask this because i would like to have the DataContext in every form but i realized that, if i change some enity in one DataContext, i have ro refresh it, if used before.

例如form1:

db = GetContext()
item=(from p in db.Table where p.id=1 select p)

以另一种形式

db = GetContext()
item=(from p in db.Table where p.id=1 select p)
item.value="test"

回到我必须做的原始表格

back on the original form i have to do

db.Refresh(RefreshMode.OverwriteCurrentValues, item)

即使我做了新的

item=(from p in db.Table where p.id=1 select p)

(不刷新)该值将不会更新

(without the refresh) the value will not be updated

DataContext线程安全吗?

Is DataContext threadsafe?

推荐答案

使用DataContext作为单例时不好DataContext使用工作单元模式实现内部有内部高速缓存,内部高速缓存的目的是避免往返数据库和进行更改跟踪.保持DataContext为单例将使内部缓存增加,然后暂时导致内存泄漏.

It is not okay when using DataContext as singleton, DataContext is implemented using Unit of Work pattern with internal cache inside, purpose of internal cache is to avoid the round trips to database and for changes tracking. Keeping DataContext as singleton would make internal cache increasing then lead to memory-leak for the time being.

最佳实践是DataContext的生存期应该是每个线程的,大多数IoC容器都支持此功能,只需选择一个并使用即可.

The best practice is the lifetime of DataContext should be per thread, most of IoC containers support this, just choose one and use.

DataContext不是线程安全的,因此大概是使用静态构造函数或Lazy<>

DataContext is not thread-safe, so presumably you implemented thead-safe singleton using static constructor or Lazy<>

这篇关于Linq和DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆