HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Redundant DataContext ? - LINQ to SQL

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
redundantlinqdatacontextsql

Problem

This seems like a pretty basic question, so bear with me...Say I have two (or many) methods in the same class that need a LINQ to SQL DataContext. Additionally, I am needing the DataContext in other classes as well. Does it make sense to create the new DataContext every time?

Should I be creating this DataContext in a different data access class and then inheriting it on each page? I feel like this is the way it should be done, but I'm still learning LINQ to SQL and just looking for some best practices. Can anyone point me to good examples of this?

Thanks,

Code for reference:

protected void LoadProducts()
{
    StoreDataClassesDataContext db = new StoreDataClassesDataContext();
    var query = from p in db.Products

            select new
            {
             p.ProductID, 
             p.Description,
             p.Price
            };

    dgProducts.DataSource = query;
    dgProducts.DataBind();
}

protected void LoadSales()
{
    StoreDataClassesDataContext db = new StoreDataClassesDataContext();
    var query = from s in db.Sales 

                select new 
                { 
                s.SaleID,
                s.SaleDate,
                s.Total
                };

    dgSales.DataSource = query;
    dgSales.DataBind();
}

Solution

I can't make a thorough review right now, but here's a quick fix that should help you structure things up.

What you have is probably working, but you're mixing-up presentation with data concerns. I don't think these methods should be returning void. Picture this:

protected IEnumerable LoadSales()
{
    using (var db = new StoreDataClassesDataContext())
    {
        var result = db.Sales.Select(s => new SalesInfo { 
                                                SaleId = s.SaleID,
                                                SaleDate = s.SaleDate,
                                                Total = s.Total })
                             .ToList();
        return result;
    }
}


What you get is a bunch of SalesInfo objects that contain your query results. Bind that to your UI instead.

It's probably normal you're re-creating the context everytime, you want these things to be as short-lived as possible.

Code Snippets

protected IEnumerable<SalesInfo> LoadSales()
{
    using (var db = new StoreDataClassesDataContext())
    {
        var result = db.Sales.Select(s => new SalesInfo { 
                                                SaleId = s.SaleID,
                                                SaleDate = s.SaleDate,
                                                Total = s.Total })
                             .ToList();
        return result;
    }
}

Context

StackExchange Code Review Q#39404, answer score: 10

Revisions (0)

No revisions yet.