[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

How to close linq to sql connection in database access layer

Posted on 2010-08-20
9
Medium Priority
?
968 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 64

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
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 
LVL 64

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 64

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 64

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 64

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

Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

649 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