Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 2 – Creating Object Mapping – Creating an Object and Providing Attributes

1. Add the following attributes for Customer to create the mapping to the database Customers table that includes columns named CustomerID and City. Here you will only map two columns in the single Customers table in Northwind.

 

[Table(Name = "Customers")]

public class Customer

{

[Column]

public string CustomerID { get; set; }

[Column]

public string City { get; set; }

 

public override string ToString()

{

return CustomerID + "\t" + City;

}

}

 

 

2. Return to the ObjectQuery method. As you did for in-memory collections, XML, and DataSet, again query to find customers that live in London. Notice that minimal changes are required. After creating a data connection you are able to get rows out of the Customers table and select those rows for customers that live in London, returning them as IEnumerable<Customer>.

 

static void ObjectQuery()

{

var db = new DataContext

(@"Data Source=.\sqlexpress;Initial Catalog=Northwind");

var results = from c in db.GetTable<Customer>()

where c.City == "London"

select c;

foreach (var c in results)

Console.WriteLine("{0}\t{1}", c.CustomerID, c.City);

}

 

The DataContext object used in the ObjectQuery method is the main conduit through which objects are retrieved from the database and changes are submitted.

 

3. You need to replace the connection string here with the correct string for your specific connection to Northwind. If you’ve done the previous exercise about LINQ to DataSet, you can find this string in the generated app.config file in the project. You will see later that after generating strongly typed classes with the designer, it is not necessary to embed the connection string directly in your code like this.

4. Press Ctrl+F5 to build and run the application. After viewing the results press any key to terminate the application.

5. Now add the following line to print the generated SQL query that runs on the database:

 

static void ObjectQuery()

{

DataContext db = new DataContext(

@"Data Source=.\sqlexpress;Initial Catalog=Northwind");

db.Log = Console.Out;

var results = from c in db.GetTable<Customer>()

where c.City == "London"

select c;

foreach (var c in results)

Console.WriteLine("{0}\t{1}", c.CustomerID, c.City);

 

}

 

6. Press Ctrl+F5 to build and run the application. After viewing the results and the generated SQL query, press any key to terminate the application.

 


Date: 2015-02-03; view: 725


<== previous page | next page ==>
Task 4 – Querying a DataSet | Task 5 – Querying using Expressions
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.005 sec.)