简体   繁体   English

Linq和DataContext

[英]Linq and DataContext

Would it be ok to have only one DataContext per app and share that through an singleton? 每个应用程序只有一个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. 我之所以这样问是因为我想以每种形式使用DataContext,但是我意识到,如果我在一个DataContext中更改了一些实体,那么如果之前使用过,我会对其进行刷新。

eg form1: 例如form1:

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

on another form 在另一种形式

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)

even if i do a new 即使我做了一个新的

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

(without the refresh) the value will not be updated (不刷新)该值将不会更新

Is DataContext threadsafe? DataContext线程安全吗?

Would it be ok to have only one DataContext per app and share that through an singleton? 每个应用程序只有一个DataContext并通过单例共享它是否可以?

Well, that's certainly not what it's designed for - and if you had multiple threads performing multiple operations, it certainly wouldn't be a good idea. 好吧,那肯定不是它的设计目的 -如果您有多个线程执行多项操作,那肯定不是一个好主意。

Just like database connections, it's best to create the context when you need it, do whatever you need to do, then create a new one when you've got a new set of operations to perform. 就像数据库连接一样,最好在需要时创建上下文,执行所需的任何操作,然后在要执行一组新的操作时创建一个新的上下文。

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. 当使用DataContext作为单例时,这是不正确的DataContext是使用内部装有内部缓存的工作单元模式实现的 ,内部缓存的目的是避免往返数据库和进行更改跟踪。 Keeping DataContext as singleton would make internal cache increasing then lead to memory-leak for the time being. DataContext保持为单例将使内部缓存增加,然后暂时导致内存泄漏。

The best practice is the lifetime of DataContext should be per thread, most of IoC containers support this, just choose one and use. 最佳实践是DataContext的生存期应该是每个线程,大多数IoC容器都支持此功能,只需选择一个即可使用。

DataContext is not thread-safe, so presumably you implemented thead-safe singleton using static constructor or Lazy<> DataContext不是线程安全的,因此大概是使用静态构造函数或Lazy<>实现了ad-safe单例

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

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