?
Solved

How to close linq to sql connection in database access layer

Posted on 2010-08-20
9
Medium Priority
?
962 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 63

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
DFW AZURE MEETUP TONIGHT FRI 6PM

We will be discussing what Azure Stack is, how does it fit into the suit of offerings that Azure has currently, and where can it fit into your organizations technology stack. We will also be discussing limitations of the platform while covering various applicable scenarios.

 
LVL 63

Accepted Solution

by:
Fernando Soto earned 2000 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
 
LVL 63

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 63

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 63

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

DFW AZURE MEETUP TONIGHT FRI 6PM

We will be discussing what Azure Stack is, how does it fit into the suit of offerings that Azure has currently, and where can it fit into your organizations technology stack. We will also be discussing limitations of the platform while covering various applicable scenarios.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Suggested Courses

752 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