Yes, you can do this by using a projection a.k.a. select
. LINQ to SQL select will enable to optimize the query and retrieves only what is needed. There are two basic scenarios. One traveling up the relational tree, from many to one, and the other travelling down, from one to many. Here is an example of many to one:
var unshippedOrders =
from order in db.Orders
where order.ShipDate == null
select
{
OrderId = order.Id,
CustomerId = order.Customer.Id,
CustomerName = order.Customer.Name
};
And here is an example from one to many:
var unshippedOrdersPerCustomer =
from customer in db.Customers
select
{
CustomerId = customer.Id,
CustomerName = customer.Name
UnshippedOrders =
from order in customer.Orders
where order.ShipDate == null
select
{
OrderId = order.Id,
OrderPrice = order.Price
}
};
As you can see, in the second query I have another sub query, LINQ to SQL will resolve this for you. In my examples I used anonymous types, but you can also use plain old named types. I think you can even mix your LINQ to SQL code with your LINQ to XML by creating XElement nodes right in your LINQ to SQL query :-). The sky is the limit.
What the heck, let me give an example if LINQ to SQL+XML.
XElement xml = new XElement("customers",
from customer in db.Customers
select new XElement("customer",
from order in customer.Orders
where order.ShipDate == null
select new XElement("order",
new XAttribute("id", order.Id),
new XAttribute("price", order.Price)
)
));
Console.WriteLine(xml);