静态方法是否适合 Linq To SQL DAL?

发布于 2024-08-21 04:23:06 字数 750 浏览 6 评论 0原文

我在 DAL 中使用 Linq to SQL,并且听说过有关在 Web 应用程序中使用静态方法的各种事情(关于线程/并发问题)。目前,我创建了一个测试 DAL,它似乎运行良好。但是,由于它是静态的,我创建它的方式有什么问题吗?

    public static class TestDAL
    {


        public static bool GetUserAddress(string username)
        {
            testDBDataContext dbContext = new testDBDataContext();
            //Linq code goes here

        }


        public static void InsertUserNumber(int userID)
        {
            testDBDataContext dbContext = new testDBDataContext();
            //...
            dbContext.UserDetails.InsertOnSubmit(nUser);
            dbContext.SubmitChanges();

        }

       //etc... All the methods are created in the same way 


    }

这种方法对于Web应用来说可以吗,或者在生产环境中会出现问题吗?

谢谢。

I'm using Linq to SQL for my DAL and have heard various things about using static methods in a web application (regarding threading/concurrency issues). At the moment, I created a test DAL, which seems to be functioning fine. However, are there any problems with the way I've created it, since it's static?

    public static class TestDAL
    {


        public static bool GetUserAddress(string username)
        {
            testDBDataContext dbContext = new testDBDataContext();
            //Linq code goes here

        }


        public static void InsertUserNumber(int userID)
        {
            testDBDataContext dbContext = new testDBDataContext();
            //...
            dbContext.UserDetails.InsertOnSubmit(nUser);
            dbContext.SubmitChanges();

        }

       //etc... All the methods are created in the same way 


    }

Is this method fine for a web application, or will there be problems in a production environment?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

把梦留给海 2024-08-28 04:23:06

只要您的静态方法不使用任何共享状态(类级状态或其他全局状态),它们本身就不会导致在多线程环境中运行的任何问题。每个静态方法调用都会创建其自己的局部变量的副本。

As long as your static methods don't use any shared state (class-level state or other global state), they won't themselves cause any problems running in a multithreaded environment. Each static method invocation will create copies of its own local variables.

就我个人而言,我会避免静态方法,因为它会使代码更难测试。在测试使用 DAL 的代码时,您将无法轻松模拟 DAL。请注意,这并不是 LINQ 或数据访问层所独有的,它只是代码的一个函数,是类方法而不是实例方法。

Personally I would avoid static methods as it will make this code much harder to test around. You won't be able to easily mock out the DAL when testing code that uses it. Note that this isn't unique to LINQ or data access layers, it's just a function of the code being a class method rather than an instance method.

信仰 2024-08-28 04:23:06

从您提供的代码片段来看,并不清楚各种方法的作用。在我看来,只要使用局部变量,它就是安全的。

From the snippet you provided it is not very clear what the various methods do. The way I see it, as long as you are using local variables, it is safe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文