Wednesday, April 02, 2008

In my previous post about using LINQ to SQL in multi layered apps, I mentioned that this query was not optimal because I would need to build the POCOs from the objects returned by LINQ.  This would mean that objects would be created twice. 

var q = from o in ctx.Orders
        where o.CustomerID == id
        select new { Detail = o.Order_Details, CustomerID = o.CustomerID, OrderDate = o.OrderDate, OrderID = o.OrderID, ShippedDate = o.ShippedDate, ShipCity = o.ShipCity };

Not ideal so I asked if anyone had an idea on how to do that.  Stefan Sedich suggested this query:

var q = from o in ctx.Orders
where o.CustomerID == id
select new TransportObjects.Northwind.Order {

Detail = o.Order_Details.Select(item => new  TransportObjects.Northwind.OrderDetail {
ProductID = item.ProductID 
}).ToArray(),

CustomerID = o.CustomerID,
OrderDate = o.OrderDate,
OrderID = o.OrderID,
ShippedDate = o.ShippedDate,
ShipCity = o.ShipCity};

Cool!  The query returns the Order complex object with the Detail property filled from orders Details.

Thanks a lot Stefan!

 

Wednesday, April 02, 2008 7:04:54 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

Theme design by Jelle Druyts