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: }
Tagged with: LINQ
6 Responses to Use SqlConnection With LINQ To SQL
Leave a Reply Cancel reply
Top Posts
- LINQ To SQL Tutorial
- LINQ To SQL Join On Multiple Conditions
- Code Sample: Programmatically Download File Using C#
- Windows 7 Control Panel In Classic Mode
- More Details Emerge On Microsoft Master Certification
- Use SqlConnection With LINQ To SQL
- Free Icons And Images With Visual Studio 2008
- Capture XML In WCF Service
- Dynamic Sort With LINQ
- StyleCop Tutorial
Tags
.Net 2010 ADO.NET ASP.NET Azure Blogging Books Browsers C# Certification Cloud Computing Code Snippets Community Data Services Eclipse Entity Framework Google IDE Java LINQ Mac Microsoft Museum NetBeans Office Oracle REST SharePoint Silverlight SQL Server T-SQL Tips Tools Training Visual Studio Visual Studio 2010 WCF Web Windows Windows 7 Windows Forms Windows Live WMI WPF XAML


I tried this code but getting losts of errors.
I can’t use var in my asp.net apps
What is the exact error you are getting?
I am assuming that you are working with .NET 3.5 or .NET 3.5 sp1
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
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/
Hi,
I want to impersonate the DB-connect with special domain credentials (not in connection string). How can this be done?
Thanks
Thilo
Thilo, try something like this:
connectionString = “Data Source=”+ strIp + “;Initial Catalog=” + strDb + “;User Id=”+ strUsr +”;Password=”+strPsswrd+”;”;