LINQ to Entities,基于方法查询,查询表达式语法
初次学习LINQ to Entities,给出两种查询的示例代码。
基于方法的查询:
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
ObjectSet<Contact> contacts = AWEntities.Contacts;
ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
var query =
contacts.SelectMany(
contact => orders.Where(order =>
(contact.ContactID == order.Contact.ContactID)
&& order.OrderDate >= new DateTime(2002, 10, 1))
.Select(order => new
{
ContactID = contact.ContactID,
LastName = contact.LastName,
FirstName = contact.FirstName,
OrderID = order.SalesOrderID,
OrderDate = order.OrderDate
}));
foreach (var order in query)
{
Console.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",
order.ContactID, order.LastName, order.FirstName,
order.OrderID, order.OrderDate);
}
}
查询表达式:
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
ObjectSet<Contact> contacts = AWEntities.Contacts;
ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
var query =
from contact in contacts
from order in orders
let total = order.TotalDue
where contact.ContactID == order.Contact.ContactID
&& total >= 10000.0M
select new
{
ContactID = contact.ContactID,
LastName = contact.LastName,
OrderID = order.SalesOrderID,
total
};
foreach (var order in query)
{
Console.WriteLine("Contact ID: {0} Last name: {1} Order ID: {2} Total: {3}",
order.ContactID, order.LastName, order.OrderID, order.total);
}
}