创建静态Datacontext()或在需要时创建.哪个更好?为什么? [英] Creating static Datacontext() or Creating whenever its needed. Which is Better, and Why?

查看:51
本文介绍了创建静态Datacontext()或在需要时创建.哪个更好?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,每次调用该函数时,我都会在其中创建一个 DataContext().创建 new DataContext()的成本是多少.我可以创建一个 static DataContext()并在所有地方使用它吗?因为当SubmitChanges()失败时,DataContext会完整记录所有更改,所以当 SubmitChanges()失败.我的问题是创建静态Datacontext()在需要时创建哪个更好?

I have a function, and inside that I am creating a DataContext() everytime the function is called. What is the cost of creating a new DataContext(). Can I create a static DataContext() and use it everywhere. Because The DataContext has a full recording of all the changes when SubmitChanges() fails, is there a way I can remove those specific changes from the DataContext when SubmitChanges() fails. My Question is which is better Creating static Datacontext() or Creating whenever its needed?

推荐答案

已经对该主题进行了很多讨论,您应该

This topic has been discussed quite a bit and you should read this article about DataContext lifetime management. The short answer is that DataContext is meant to be used for a unit of work, typically a single request. DataContext objects are cheap to construct and there is no database overhead to creating one.

避免共享 DataContext 实例的主要原因是因为线程安全和更改跟踪.当您调用 SubmitChanges()时,您对存储库对象所做的每次修改都会捕获并转换为更新/插入/删除操作.使用单个 DataContext 对象时,此功能会失效.

The main reason to avoid a shared instance of DataContext is because of thread safety and change tracking. Each modification you make to a repository object is captured and translated into update/insert/delete operations when you call SubmitChanges(). This feature breaks down when using a single DataContext object.

这篇关于创建静态Datacontext()或在需要时创建.哪个更好?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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