Entity Framework query to return only partial object graphs

I have a little headache finding a solution for this particular problem. So, here it is: Let's say I have 3 tables:

  • Customers
  • Orders
  • Products

I want to get a list of customers and their orders with some filtering in some of the "Customers" and "Orders" fields and return a graph that displays only basic information about these objects. For example, the Client can have 19 fields, but I only want to read its identifier, FirstName, LastName and from orders, I only want to read NetPrice and the corresponding product identifiers in such a way that when iteration occurs in the query, the SQL that is generated is very easy and will select only those specific fields. Is this something that can be achieved? If so, how? I am very puzzled by how to do this. Thank you very much.

EDIT: Well, I managed to do it and the boy quickly! Here is how I did it:

var customers = (from customer in Context.Cutomers
                select new
                {
                    customer.ID,
                    customer.FirstName,
                    customer.LastName,
                    Orders = customer.Orders.Select(order => new
                    {
                        order.ID,
                        order.NetPrice,
                        Products = order.Products.Select(product => new
                        {
                            product.ID
                        }
                    }
                })
                .AsEnumerable()
                .Select(c => new Customer 
                {
                    c.ID,
                    //In my case, this is VERY important as it will 
                    //try to convert from IEnumerable<T> to ICollection<T> 
                    //which seems to need to be explicit.
                    Orders = c.Orders as ICollection<Order> 
                })
                .ToList();

EDIT No. 2: I was mistaken ... It compiles fine, everything works, but my products are empty ... I'm at a dead end again ...

+3
1

( , ). , , - :

var query = from c in context.Customers
            select new 
              {
                 c.Id,
                 c.FirstName,
                 c.LastName,
                 Orders = c.Orders.Select(o =>
                   new OrderPartial
                     {
                       NetPrice = o.NetPrice,
                       ProductIds = o.Products.Select(p => p.Id) 
                     })
              };
0

All Articles