How to query a SQL Server Database using LINQ

Your Ad Here

This example queries standard Microsoft Northwind sample database

 

using System;
using System.Linq;
using System.Data.Linq;
using northwindEntity;
Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind");
var custs =from c in db.Customers
                 where c.City == "Rio de Janeiro"
                 select c;
foreach (var cust in custs)
Console.WriteLine("{0}", cust.CompanyName);

You may need to change the connection string that is passed to the Northwind constructor in above code for the connection to be properly made.

In the above given example, we are using System.linq and System.Data.Linq name spaces and our own NorthwindEntity namespace which contains the classes for northwind database.you u can see that I added a using directive for the northwindEntity namespace. For this example to work,you must use the entity framework class, or the Object Relational Designer, to generate entity classes for the targeted database, which in this example is the Microsoft Northwind sample database. . The generated entity classes are created in the northwindEntity namespace, which I specify when generating them. I then add the entity generated source module to my project and add the using directive for the northwindEntity namespace.  Rest of example is self explanatory.

 

Happy Coding.

Subscribe
Posted in Labels: kick it on DotNetKicks.com |

0 comments: