简体   繁体   English

数据库访问的静态类?

[英]static classes for database access?

I am using DataClassesDataContext to map all the tables from the db into my asp.net application. 我正在使用DataClassesDataContext将db中的所有表映射到我的asp.net应用程序中。

For doing CRUD operations i have made static classes with methods, and inside every method a instantiate DataClassesDataContext. 为了进行CRUD操作,我使用方法创建了静态类,并在每个方法中实例化了DataClassesDataContext。

For instance: 例如:

public static class UserQ
{
    public static User getUserById(int userId)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        var requestedUser = (from u in db.Users
                             where u.User_id == userId
                             select u).First();
        if (requestedUser != null)
            return (User)requestedUser;
        else
            return null;
    }
}

I aam not sure if this way of doing database operations in a web application is safe? 我不确定这种在Web应用程序中执行数据库操作的方式是否安全? If not, can you suggest please a better pattern? 如果没有,你能建议一个更好的模式吗?

As DataClassesDataContext implements IDisposable , you should be wrapping it with a using directive: 由于DataClassesDataContext实现了IDisposable ,您应该使用using指令包装它:

using (DataClassesDataContext db = new DataClassesDataContext())
{
...
}

I would suggest taking a look at the Repository Pattern: 我建议看一下存储库模式:

1) Example 1 1) 实施例1
2) Example 2 (Scott Gu's first chapter from Nerd Dinner - its for MVC but the Repository pattern illustrated works w/o MVC) 2) 示例2 (Scott Gu的第一章来自Nerd Dinner - 它用于MVC,但是Repository模式说明了没有MVC的工作)

I would be very very careful about using STATIC in web applications. 在Web应用程序中使用STATIC我会非常小心。 Sometimes the bugs are so subtle that you will spend a lot of time debugging. 有时错误是如此微妙,你将花费大量时间调试。

I think bnkdev & Oded hit the nail on the head: look at repository pattern & wrap your context call in a using statement... 我认为bnkdev和Oded击中头部:查看存储库模式并在using语句中包装您的上下文调用...

HTH. HTH。

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

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