Cristian Boariu
Cristian Boariu

Reputation: 9621

static classes for database access?

I am using DataClassesDataContext to map all the tables from the db into my asp.net application.

For doing CRUD operations i have made static classes with methods, and inside every method a instantiate 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? If not, can you suggest please a better pattern?

Upvotes: 1

Views: 326

Answers (3)

Ta01
Ta01

Reputation: 31610

I would suggest taking a look at the Repository Pattern:

  1. Example 1
  2. Example 2 (Scott Gu's first chapter from Nerd Dinner - its for MVC but the Repository pattern illustrated works w/o MVC)

Upvotes: 1

Sunny
Sunny

Reputation: 6346

I would be very very careful about using STATIC in web applications. 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...

HTH.

Upvotes: 1

Oded
Oded

Reputation: 499042

As DataClassesDataContext implements IDisposable, you should be wrapping it with a using directive:

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

Upvotes: 2

Related Questions