Anonymous type to paritally load a collection in Linq to Sql


Is there a work around using anonymous type to paritally load a collection in the correct order we desire with Linq to Sql in c#?

edit | flag
William Patrick
Asked on: Jun 16, 2011 at 9:06PM

1 Answers


Suppose you have a model consisting of Customers and Orders and You want to retrieve a customer and its related orders. However you only want to retrieve orders which have freight greater then 100 dollars and order the orders collection by Ship Date. Below is the query to do this.

var db = new NorthwindEntities();
var custs = from c in db.Customers
where c.CustomerID == "ALFKI"
select new
Customer = c,
Orders = c.Orders.Where(o => o.Freight > 10.0M).OrderBy(o => o.ShippedDate)
var cust = custs.FirstOrDefault().Customer;

we are creating an anonymous type with two properties Customer and Orders. On the Orders property, I am sorting and filtering the orders collection. When we materialize the above query using FirstOrDefault, EF actually sees that orders loaded in the context points to the customer that also exist in the context, so it fixes the object graph for us, giving us the same behavior which an Include would give us.

edit | flag
Gokul A
Answered on: Jun 16, 2011 at 9:09PM

Post your Answer


Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags