I have a simple database that I use, with an EF data model to work with.
My tables looks like this:
customers table
- CustomerId
- CustomerName
Orders table
- OrderId
- CustomerID FK
- OrderDate
I’m using a helper class to query my model and in this class I have the following query:
public static List<object> GetCustomerOrdersCount()
{
using (OrdersDbEntities context = new OrdersDbEntities())
{
return context.Customers.Select(
c => new
{
CustId = c.CustomerId,
CustName = c.CustomerName,
OrdersCount = c.Orders.Count
}).ToList<object>();
}
}
The only return type I could use with this method is a List<object>
And finally my question is: how do I use the data received from this query?
The only way I can read the values is by reflection:
List<object> custs = Dal.GetCustomerOrdersCount();
foreach (var customer in custs)
{
var properties = customer.GetType().GetProperties();
foreach (var data in properties)
{
var value = data.GetValue(custs[0], null);
}
}
I wonder if there’s a better way to do this.
The problem that I see is that you’re selecting an anonymous type, can’t you do:
That would return your complete
Customerentity, rather than an anonymous type that contains only specific members.EDIT
If the underlying problem, in regards to our conversation about lazy loading, is that you want a count of the number of orders for a given customer, without actually loading the orders, then I would do something like this: