Solved

How to close linq to sql connection in database access layer

Posted on 2010-08-20
9
953 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 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
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

821 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