1

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?

Cristian Boariu
  • 9,461
  • 13
  • 89
  • 160

3 Answers3

2

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

using (DataClassesDataContext db = new DataClassesDataContext())
{
...
}
Oded
  • 477,625
  • 97
  • 867
  • 998
1

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)

Ta01
  • 30,248
  • 12
  • 69
  • 98
  • I agree. It really will simplify things and in the case of LINQ to SQL it will increase your performance greatly if you rely on IQueryable. Take a look here http://stackoverflow.com/questions/1223194/loading-subrecords-in-the-repository-pattern – Keith Adler Feb 08 '10 at 18:32
  • Thanks. Haven't heard about Repository Pattern before. After rading the articles i can say: Great! – Cristian Boariu Feb 08 '10 at 19:12
1

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.

Sunny
  • 6,166
  • 2
  • 24
  • 26