Solved

How to close linq to sql connection in database access layer

Posted on 2010-08-20
9
945 Views
Last Modified: 2013-11-11
I using linq to sql where I have two enties in datacontext file epar and shoppingcart

I had implemented linq to sql in my database access layer I am closing the database connection with using(..) statement

I am returning the shoppingcart as a return object to the UI but getting error.

my code where I am reading values:

Line 1:  shoppingcart cart = cartFuunctions.GetBasketItemdetails(Request.QueryString["SessionID"], Request.QueryString["ProductID"]);
Line 2:   lblpartno.Text = cart.ProductCode;
Line 3:   lblProductName.Text = cart.epar.descr;

On Line 2 I am able to read the data successfully but on Line 3 I am getting error message that connection is closed

Please see the code attached for the database access layer file

Thanks
//Database Access Layer Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DAL.LinqToSql
{
    public static class CartLinqDB
    {
        private static string _connectionString;

        private static string ConnectionString
        {
            get
            {
                return _connectionString;
            }
            set
            {
                if (string.IsNullOrEmpty(_connectionString) == false)
                {
                    BindConnection();
                }
                    _connectionString = value;
                
            }
        }

        static CartLinqDB()
        {
            //Initializing connection string
            BindConnection();
        }

        /// <summary>
        /// Initializing connection string
        /// </summary>
        private static void BindConnection()
        {
            ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        }

        /// <summary>
        /// return the basketItem details
        /// </summary>
        /// <param name="BasketItemId"></param>
        /// <returns></returns>
        public static shoppingcart GetBasketItemdetails(string SessionID, string ProductID)
        {
            shoppingcart cart;
            using (LinqToSqlDbDataContext db = new LinqToSqlDbDataContext(ConnectionString))
            {
                cart = db.shoppingcarts.Single(p => p.SessionID == SessionID && p.ProductCode==ProductID);
            }
            return cart;
        }
    }
}

Open in new window

0
Comment
Question by:shieldguy
  • 5
  • 3
9 Comments
 
LVL 21

Expert Comment

by:naspinski
ID: 33485211
There is no need to, L2S will close it automatically after each query.
http://stackoverflow.com/questions/389822/when-should-i-dispose-of-a-data-context
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 33485301
Hi shieldguy;

You state that in line 2 it works but line 3 does not.

Line 2:   lblpartno.Text = cart.ProductCode;
Line 3:   lblProductName.Text = cart.epar.descr;

What is epar in the statement, cart.epar.descr;, it looks like a reference to another table?

Fernando
0
 
LVL 1

Author Comment

by:shieldguy
ID: 33485311
yes its another table
epar and shoppingcart has one to many relation
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 33485596
Hi shieldguy;

Try making this change in your code.

Fernando
public static shoppingcart GetBasketItemdetails(string SessionID, string ProductID)

{

    shoppingcart cart;

    using (LinqToSqlDbDataContext db = new LinqToSqlDbDataContext(ConnectionString))

    {

        DataLoadOptions dlo = new DataLoadOptions();

        dlo.LoadWith<shoppingcarts>(s => s.epar);

        db.LoadOptions = dlo;

        cart = db.shoppingcarts.Single(p => p.SessionID == SessionID && p.ProductCode==ProductID);

    }

    return cart;

}

Open in new window

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 62

Expert Comment

by:Fernando Soto
ID: 33485612
You will also need this using statement at the top of the file in the DAL.

using System.Data.Linq;
0
 
LVL 1

Author Comment

by:shieldguy
ID: 33485891
Good Fernando ur solution works but is the best approach in this case should its really necessary to used using statemenst or some other way of closing connection as I build application for web application which has many user and I dont want the memory overload
Thanks
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 33485925
Also epar is a collection and so this line needs to change

lblProductName.Text = cart.epar.descr;

To something like this

lblProductName.Text = cart.epar.FirstOrDefaule().descr;

Or some other collection method to find the right one you need.
0
 
LVL 1

Author Comment

by:shieldguy
ID: 33485948
no epar is the product table and it has the primary key and shoppingcart has the foregin key so epar always return one record
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 33485984
In a case like this I would use the using statement because it disposes of the context where it is no longer needed reducing memory requirements.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now