2

I am developing a site using ASP.NET, SQL 2008 and LINQ. I want to ask about the connection string. I have made a class like that to get the datacontext in each page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DatabaseConnection
{
    static DataClassesDataContext datacontext;    
    public static DataClassesDataContext getConnection()
    {
       datacontext = new DataClassesDataContext(@"Data Source=localhost;Initial Catalog=dbname; Integrated Security=True");
        return datacontext;
    }
}

Is that a correct way to get the connection in each page?

Also about 'Data Source', when I deploy the site what will it be? And what is the difference between data source and address keywords?

1
  • In web application, you have to create & dispose data-context over a request - so I am not sure if using a singleton is an good approach. I would suggest using a factory method to create data context initialized with connection string from configuration. If you must hold the same context over a request then store it in HttpContext and write a wrapper property to get it. Commented Jun 2, 2011 at 9:54

2 Answers 2

2

That is a valid way of getting the data context instance, yes. You can use Data Source or Server I believe.

Please be aware that DataContext is IDisposable, so make sure it's not left hanging around after usage, I tend to do:

using (var context = DataHelper.GetContext())
{
   // Stuff.
}

Also, you should really put your connection strings in the configuration file:

<connectionStrings>
   <add name="Live" connectionString="blah;"/>
</connectionStrings>
Sign up to request clarification or add additional context in comments.

Comments

2

Much better if you place your Connection string on your Web.Config File

<?xml version="1.0"?>
<configuration>
    <configSections>
<connectionStrings>
    <add name="DB" connectionString="Data Source=localhost;Initial Catalog=dbname; Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>

Have a look at this:

LINQ To SQL and the Web.Config ConnectionString Value

LINQ to SQL Connection Strings with class library projects

Regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.