LINQ To SQL allows us to use a SqlConnection object to connect to a database. The way to use a SqlConnection is to pass it as a parameter to DataContext object. DataContext object has constructor which takes in a IDbConnection and SqlConnection implements this Interface. Here I create a SqlConnection object and use it to establish a connection to database.

   1: // Create a Connection String
   2: string connectionString
   3:     = "Data Source=.;Initial Catalog=Northwind2;Integrated Security=True";
   4:
   5: // Create a SqlConnection
   6: using (SqlConnection connection = new SqlConnection(connectionString))
   7: {  // Create DataContext and pass in the connection  
   8:     using (NorthwindDataContext context = new NorthwindDataContext(connection))
   9:     {    var query = from c in context.Customers
  10:                      select c.CompanyName;
  11:
  12:         foreach (var item in query)
  13:         {
  14:             Console.WriteLine(item);
  15:         }
  16:     }
  17: }
Tagged with:
 

6 Responses to Use SqlConnection With LINQ To SQL

  1. Patrick says:

    I tried this code but getting losts of errors.
    I can’t use var in my asp.net apps

  2. Deepak says:

    What is the exact error you are getting?

    I am assuming that you are working with .NET 3.5 or .NET 3.5 sp1

  3. Patrick says:

    Error cannot convert char to string.
    When i use “var” in my code behind in my asp.net app.
    Do i need VS 2008 plus .net framework 3.5 sp1 to run this?
    Thanks

  4. Deepak says:

    You must have atleast .NET Framework 3.5. LINQ is part of .NET Framework 3.5. You can also download Visual Studio Express which is a free download.

    http://www.microsoft.com/Express/

  5. Thilo says:

    Hi,

    I want to impersonate the DB-connect with special domain credentials (not in connection string). How can this be done?

    Thanks

    Thilo

  6. Bob says:

    Thilo, try something like this:

    connectionString = “Data Source=”+ strIp + “;Initial Catalog=” + strDb + “;User Id=”+ strUsr +”;Password=”+strPsswrd+”;”;

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>