Giffyguy
Giffyguy

Reputation: 21292

Very Basic LINQ to SQL Question

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.

Upvotes: 0

Views: 405

Answers (2)

J.W.
J.W.

Reputation: 18181

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.

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

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...)

Upvotes: 2

Related Questions