Solved

How to close linq to sql connection in database access layer

Posted on 2010-08-20
9
960 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 63

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
 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

707 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