Linq and DataContext

无人久伴 提交于 2019-12-12 09:18:28

问题


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

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.

eg 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?


回答1:


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.

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

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




回答2:


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

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.



来源:https://stackoverflow.com/questions/12871666/linq-and-datacontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!