Home / Programming / Blog article: Use SqlConnection With LINQ To SQL

| RSS

Use SqlConnection With LINQ To SQL

September 16th, 2008 | 4 Comments | Posted in Programming

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: }
Leave a Reply 20220 views, 4 so far today |
Tags:
Follow Discussion

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

Leave a Reply





Switch to our mobile site