views:

140

answers:

2

My question is regarding a code sample from this MSDN article:
Getting Started (LINQ to SQL)

The following code is listed in the article:

// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");

var companyNameQuery =
    from cust in nw.Customers
    where cust.City == "London"
    select cust.CompanyName;

foreach (var customer in companyNameQuery)
{
    Console.WriteLine(customer);
}

How is "nw" created? Where does the data-type "Northwnd" come from? How am I supposed to access MY database in this way? I am writing an application that accesses a SQL server, and I have added the appropriate DBML file(s) to my project using the server explorer. But I have no idea how to write this line of code to access my DB.

+1  A: 

The DataContext type and all entities are generated from your dbml file automatically, you have to check the DataContext Name on the designer, right click on any blank spot on the diagram, click Properties and check for the Name property on the Code Generation section.

I think that was an early article, now the DataContext are named by default with the DataContext suffix (i.e: NorthwindDataContext, MyDatabaseDataContext, etc...)

CMS
Perfect answer! Thanks a lot! This is just what I needed to know.
Giffyguy
You're welcome!
CMS
A: 

Northwnd is a datacontext object, and after you added your dbml file, this class is created for you by the designer and you can use it.

By initialize it using new, you are opening a connection to the database.

var companyNameQuery =
    from cust in nw.Customers
    where cust.City == "London"
    select cust.CompanyName;

will be translated into sql by LINQ2SQL provider, and return you the result.

J.W.