|
Use SqlConnection With LINQ To SQL
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 |
Get Updates By Email
Popular Post
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Free Icons And Images With Visual Studio 2008
- Windows 7 Control Panel In Classic Mode
- Dynamic Sort With LINQ
- Use SqlConnection With LINQ To SQL
- StyleCop Tutorial
- Write To Vista Event Log Using C#
- More Details Emerge On Microsoft Master Certification
Tag Cloud
Code Snippets
- Get Current Windows User In C#
- Get Width And Height Of Image In C#
- Get Windows Registry Size With WMI And C#
- Reverse Array Elements Using C#
- Convert Hexadecimal To Number In C#
- Get Free Disk Space Using T-SQL
- SQL Server 2008 – Get All Indexes In A Database
- Get Name Of Current Executing Assembly In C#
- Get CD Or DVD Drive Information Using WMI And C#
- Get Last Row From Table Using LINQ To SQL


October 2nd, 2008 at 5:59 pm
I tried this code but getting losts of errors.
I can’t use var in my asp.net apps
October 2nd, 2008 at 6:45 pm
What is the exact error you are getting?
I am assuming that you are working with .NET 3.5 or .NET 3.5 sp1
October 3rd, 2008 at 3:23 pm
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
October 3rd, 2008 at 7:33 pm
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/