非常基本的LINQ to SQL问题

时间:2009-07-01 23:33:41

标签: c# .net sql linq linq-to-sql

我的问题是关于此MSDN文章中的代码示例:
Getting Started (LINQ to SQL)

文章中列出了以下代码:

// 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);
}

“nw”是如何创建的?数据类型“Northwnd”来自哪里?我怎么能以这种方式访问​​我的数据库?我正在编写一个访问SQL服务器的应用程序,并且已使用服务器资源管理器将相应的DBML文件添加到我的项目中。但我不知道如何编写这行代码来访问我的数据库。

2 个答案:

答案 0 :(得分:1)

DataContext类型和所有实体都是自动从dbml文件生成的,您必须检查设计器上的DataContext Name,右键单击图上的任何空白处,单击 Properties 并检查代码生成部分的 Name 属性。

我认为这是一篇早期的文章,现在DataContext默认使用DataContext后缀命名(即:NorthwindDataContext,MyDatabaseDataContext等...)

答案 1 :(得分:0)

Northwnd是一个datacontext对象,在您添加dbml文件后,设计人员会为您创建此类,您可以使用它。

通过使用new初始化它,您将打开与数据库的连接。

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

将由LINQ2SQL提供程序翻译成sql,并返回结果。

相关问题