现在的位置: 首页 > 综合 > 正文

光脚丫学LINQ(016):创建简单对象模型和LINQ查询(C#)

2012年05月30日 ⁄ 综合 ⁄ 共 5148字 ⁄ 字号 评论关闭

视频演示:http://u.115.com/file/f2e3bc874c

本演练提供了复杂性最低的基本端对端 LINQ to SQL 方案。您将创建一个可为示例 Northwind 数据库中的 Customers 表建模的实体类。 然后您将创建一个简单查询,用于列出位于伦敦的客户。
本演练在设计上是面向代码的,以帮助说明 LINQ to SQL 概念。 一般来说,您会使用对象关系设计器来创建对象模型。 有关更多信息,请参见对象关系设计器(O/R 设计器)。

创建LINQ to SQL解决方案
此任务为第一项任务,在此任务中,您要创建一个 Visual Studio 解决方案,此解决方案包含生成和运行 LINQ to SQL 项目所必需的引用。
1、 在 Visual Studio 的“文件”菜单上指向“新建”,然后单击“项目”。
2、 在“新建项目”对话框的“项目类型”窗格中,单击“Visual C#”。
3、 在“模板”窗格中,单击“控制台应用程序”。
4、 在“名称”框中,键入 LinqConsoleApp。
5、 在“位置”框中,确认要用于存储项目文件的位置。
6、 单击“确定”。

添加LINQ引用和指令
本演练用到默认情况下您的项目中可能未安装的程序集。 如果在您的项目中未将 System.Data.Linq 作为引用列出(在“解决方案资源管理器”中展开“引用”节点),请按照以下步骤中的说明添加它。
1、 在“解决方案资源管理器”中,右击“引用”,然后单击“添加引用”。
2、 在“添加引用”对话框中,依次单击“.NET”、System.Data.Linq 程序集和“确定”。
此程序集即被添加到项目中。
3、 在“Program.cs”的顶部添加以下指令:

using System.Data.Linq;   
using System.Data.Linq.Mapping;  
using System.Data.Linq;
using System.Data.Linq.Mapping; 

将类映射到数据库表
在此步骤中,您将创建一个类,并将其映射到数据库表。 这样的类称为“实体类”。 请注意,只需添加 TableAttribute 属性即可完成映射。 Name 属性指定数据库中的表的名称。
将下面的代码键入或粘贴到 Program.cs 中紧靠在 Program 类声明上方的位置:

[Table(Name = "Customers")]   
public class Customer   
{   
}  
[Table(Name = "Customers")]
public class Customer
{
} 

在类中指定用于表示数据库列的属性
在此步骤中,您要完成几项任务。
您要使用 ColumnAttribute 属性 (Attribute) 指定实体类中的 CustomerID 和 City 属性 (Property) 表示数据库表中的列。
您要指定 CustomerID 属性表示数据库中的主键列。
您要指定 _CustomerID 和 _City 字段用作私有存储字段。 然后,LINQ to SQL 就可以直接存储和检索值,而不用使用可能包含业务逻辑的公共访问器。

表示两个数据库列的特性
将下面的代码键入或粘贴到 Program.cs 中 Customer 类的大括号内。

private string _CustomerID;   
[Column(IsPrimaryKey = true, Storage = "_CustomerID")]   
public string CustomerID   
{   
    get  
    {   
        return this._CustomerID;   
    }   
    set  
    {   
        this._CustomerID = value;   
    }   
  
}   
  
private string _City;   
[Column(Storage = "_City")]   
public string City   
{   
    get  
    {   
        return this._City;   
    }   
    set  
    {   
        this._City = value;   
    }   
}  
private string _CustomerID;
[Column(IsPrimaryKey = true, Storage = "_CustomerID")]
public string CustomerID
{
    get
    {
        return this._CustomerID;
    }
    set
    {
        this._CustomerID = value;
    }

}

private string _City;
[Column(Storage = "_City")]
public string City
{
    get
    {
        return this._City;
    }
    set
    {
        this._City = value;
    }
}

指定与Northwind数据库的连接
在此步骤中,使用 DataContext 对象在基于代码的数据结构与数据库本身之间建立连接。 DataContext 是您从数据库中检索对象和提交更改的主要通道。
您还可以针对数据库中的 Customers 表声明 Table<Customer> 作为查询的类型化逻辑表。 您将在后续步骤中创建和执行这些查询。
将下面的代码键入或粘贴到 Main 方法中。
请注意,假定 Northwind.mdf 文件位于 linqtest5 文件夹中。 有关更多信息,请参见本演练前面介绍的“先决条件”一节。 

// Use a connection string.   
DataContext db = new DataContext(@"C:\linqtest5\Northwind.mdf");   
  
// Get a typed table to run queries.   
Table<Customer> Customers = db.GetTable<Customer>();  
// Use a connection string.
DataContext db = new DataContext(@"C:\linqtest5\Northwind.mdf");

// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();

创建简单查询
在此步骤中,您将创建一个查询,查找数据库中的 Customers 表内的哪些客户位于伦敦。 此步骤中的查询代码只描述查询,它不执行查询。 这种方法称为“延迟执行 ”。 有关更多信息,请参见 LINQ 查询简介 (C#)。
您还将生成一个日志输出,显示 LINQ to SQL 生成的 SQL 命令。 此日志记录功能(使用 Log)对调试有帮助,并有助于确定发送给数据库的命令是否准确地表示您的查询。
将下面的代码键入或粘贴到 Table<Customer> 声明后面的 Main 方法中。

// Attach the log to show generated SQL.   
db.Log = Console.Out;   
  
// Query for customers in London.   
IQueryable<Customer> AllCustomers =   
    from Customer in Customers   
    where Customer.City == "London"  
    select Customer;  
// Attach the log to show generated SQL.
db.Log = Console.Out;

// Query for customers in London.
IQueryable<Customer> AllCustomers =
    from Customer in Customers
    where Customer.City == "London"
    select Customer;

执行查询
在此步骤中,您将实际执行查询。您在前面步骤中创建的查询表达式只有在需要结果时才会进行计算。当您开始 foreach 迭代时,将会针对数据库执行 SQL 命令,并将对象具体化。
1、 将下面的代码键入或粘贴到 Main 方法的末尾(在查询说明之后)。

foreach (Customer Customer in AllCustomers)   
{   
    Console.WriteLine("ID={0}, City={1}",   
        Customer.CustomerID,   
        Customer.City);   
}   
  
// Prevent console window from closing.   
Console.ReadLine();  
foreach (Customer Customer in AllCustomers)
{
    Console.WriteLine("ID={0}, City={1}",
        Customer.CustomerID,
        Customer.City);
}

// Prevent console window from closing.
Console.ReadLine();

2、 按 F5 调试该应用程序。
说明
如果您的应用程序产生运行时错误,请参见 通过演练学习 (LINQ to SQL) 中的“疑难解答”一节。
3、 控制台窗口中的查询结果应显示如下:

SELECT [t0].[CustomerID], [t0].[City]   
FROM [Customers] AS [t0]   
WHERE [t0].[City] = @p0   
-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]   
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1   
  
ID=AROUT, City=London   
ID=BSBEV, City=London   
ID=CONSH, City=London   
ID=EASTC, City=London   
ID=NORTS, City=London   
ID=SEVES, City=London  
SELECT [t0].[CustomerID], [t0].[City]
FROM [Customers] AS [t0]
WHERE [t0].[City] = @p0
-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1

ID=AROUT, City=London
ID=BSBEV, City=London
ID=CONSH, City=London
ID=EASTC, City=London
ID=NORTS, City=London
ID=SEVES, City=London 

4、 在控制台窗口中按 Enter 以关闭应用程序。

完整代码

using System;   
using System.Collections.Generic;   
using System.Linq;   
using System.Text;   
using System.Data.Linq;   
using System.Data.Linq.Mapping;   
  
namespace Demo02   
{   
    [Table(Name = "Customers")]   
    public class Customer   
    {   
        private string _CustomerID;   
        [Column(IsPrimaryKey = true, Storage = "_CustomerID")]   
        public string CustomerID   
        {   
            get  
            {   
                return this._CustomerID;   
            }   
            set  
            {   
                this._CustomerID = value;   
            }   
        }   
  
        private string _City;   
        [Column(Storage = "_City")]   
        public string City   
        {   
            get  
            {   
                return this._City;   
            }   
            set  
            {   
                this._City = value;   
            }   
        }   
    }   
  
    class Program   
    {   
        static void Main(string[] args)   
        {   
            // Use a connection string.   
            DataContext db = new DataContext(@"C:\linqtest5\Northwind.mdf");   
  
            // Get a typed table to run queries.   
            Table<Customer> Customers = db.GetTable<Customer>();   
  
            // Attach the log to show generated SQL.   
            db.Log = Console.Out;   
  
            // Query for customers in London.   
            IQueryable<Customer> AllCustomers =   
                from Customer in Customers   
                where Customer.City == "London"  
                select Customer;   
  
            foreach (Customer Customer in AllCustomers)   
            {   
                Console.WriteLine("ID={0}, City={1}",   
                    Customer.CustomerID,   
                    Customer.City);   
            }   
  
            // Prevent console window from closing.   
            Console.ReadLine();   
        }   
    }   
}  

抱歉!评论已关闭.