Tải bản đầy đủ - 0 (trang)
9-14. Perform a LINQ Query

9-14. Perform a LINQ Query

Tải bản đầy đủ - 0trang

CHAPTER 9 ■ DATABASE ACCESS



Solution

Create or obtain an instance of DataTable (see recipes 9-12 and 9-13) and call the AsEnumerable instance

method to obtain an IEnumerable, which can be used as a data source for LINQ queries.



How It Works

LINQ performs queries on the IEnumerable<> type, which you can obtain from instances of DataTable

using the AsEnumerable instance method. When using SQLDataAdapter to populate instances of DataTable

with data (see recipe 9-12), remember that you are working with cached data that will not reflect

changes made to the database. See Chapter 16 for recipes that demonstrate LINQ features.



The Code

The following example creates a DataSet that contains a DataTable with all of the rows of the Northwind

Region table, and then performs a LINQ query using the DataTable as the data source:

using

using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.Data;

System.Data.SqlClient;



namespace Apress.VisualCSharpRecipes.Chapter09

{

class Recipe09_14

{

static void Main(string[] args)

{

// Create a new SqlConnection object.

using (SqlConnection con = new SqlConnection())

{

// Configure the SqlConnection object's connection string.

con.ConnectionString = @"Data Source = .\sqlexpress;" +

"Database = Northwind; Integrated Security=SSPI";

// Open the database connection.

con.Open();

// Create the query string.

string query = "SELECT * from Region";

// Create the data set.

DataSet dataset = new DataSet();



469



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Create the SQL data adapter.

SqlDataAdapter adapter = new SqlDataAdapter(query, con);

// Create the command builder so we can do modifications.

SqlCommandBuilder commbuilder = new SqlCommandBuilder(adapter);

// Populate the data set from the database.

adapter.Fill(dataset);

// Obtain the data table.

DataTable table = dataset.Tables[0];

// Perform the LINQ query.

IEnumerable result = from e in table.AsEnumerable()

where e.Field(0) < 3

select e.Field(1);

// Enumerate the results of the LINQ query.

foreach (string str in result)

{

Console.WriteLine("Result: {0}", str);

}

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}

Running the program gives the following results:

Result: Eastern

Result: Western



Main method complete. Press Enter.



470



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



9-15. Perform a LINQ Query with Entity Types

Problem

You need to work with types when using LINQ.



Solution

Define and annotate types with the Table and Column annotations and use

System.Data.Linq.DataContext to access the data in your database.



How It Works

LINQ includes support for entity classes, which map the schema from your database into .NET types.

You create an entity type by defining a partial class with members representing columns in a given

database table and apply annotations from the System.Data.Linq.Mapping namespace to give the .NET

Framework details of how to map from the table to instances of your entity type.



■ Tip Visual Studio can automatically create types for you. Select the Add a New Item option for your project, and

then select LINQ to SQL Classes to start a wizard that will generate the source files you require.



The first annotation to apply is Table, which creates the relationship between the partial class you

have defined and the table in the database—this annotation takes one argument, which is, not

surprisingly, the name of the table in question. You must then define one member for each column in

the table (ensuring that the member type matches the schema type for the database table), and apply the

Column annotation. For the Region table in the Northwind database, we would create a class like this:

[Table(Name = "Region")]

public partial class Region

{

[Column]

public int RegionID;

[Column]

public string RegionDescription;

}

To use the entity type, create an instance of System.Data.Linq.DataContext, passing in a

SqlConnection to your database as the constructor argument. You then call the DataContext.GetTable<>

instance method using your entity class as the type annotation—for example:

Table regionstable = context.GetTable();

The result from the GetTable method is a strongly typed instance of System.Data.Linq.Table, which

you can use as the data source for a LINQ query. In the clauses of the query, you can refer to the



471



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



members of your entity type to perform filters and select results—see the code for this recipe for a

demonstration.



■ Tip LINQ entity types have a lot of features beyond what we have demonstrated here—see the .NET

documentation for further details. The LINQ to SQL home page is a good starting point:

http://msdn.microsoft.com/en-us/library/bb386976(VS.100).aspx.



The Code

The following example defines the type Region to represent rows in the Northwind Region table. A

DataContext is created to access the data, and the Region table is used as the basis for a LINQ query,

returning an IEnumeration as the result.



■ Note You must add the System.Data.Linq.dll assembly to your project in order to use the

System.Data.Linq and System.Data.Linq.Mapping namespaces.



using

using

using

using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.Data;

System.Data.SqlClient;

System.Data.Linq;

System.Data.Linq.Mapping;



namespace Apress.VisualCSharpRecipes.Chapter09

{

[Table(Name = "Region")]

public partial class Region

{

[Column]

public int RegionID;

[Column]

public string RegionDescription;

}

class Recipe09_15

{

static void Main(string[] args)

{



472



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

9-14. Perform a LINQ Query

Tải bản đầy đủ ngay(0 tr)

×