WCF RIA Services: don’t forget EF best practices!

To include related entities, we need to add Include attribute in metadata. (Thanks Audrey :))

Then we can use something like this:

public IQueryable<Customer> GetCustomers()
{
    return this.ObjectContext.Customers;
}

public
 IQueryable<Customer> GetCustomersWithOrders()
{
    return this.ObjectContext.Customers.Include("Orders");
}

However, as I explained in a previous post, Include method has very poor performance with current EF version.

So I advise you to avoid it!

Now the question is: how can we use Include logic avoiding Include method with WCF RIA Services?

My trick is to load Orders in another query like this:

public IQueryable<Customer> GetCustomers()
{
   
return this.ObjectContext.Customers;
}






public IQueryable<Customer> GetCustomersWithOrders()
{
   
return this.ObjectContext.Customers;
}

public override IEnumerable Query(QueryDescription queryDescription, out IEnumerable<ValidationResult> validationErrors, out int totalCount)
{
    var value = base.Query(queryDescription, out validationErrors, out totalCount);
    if (queryDescription.Method.Name == ReflectionUtil.GetMethodName(() => GetCustomersWithOrders()))
    {
        IEnumerable<string> customerIds = value.Cast<Customer>().Select(c => c.CustomerID);
        foreach (var order in ObjectContext.Orders.Where(o => customerIds.Contains(o.CustomerID))) ;
    }
    return value;
}



With this code for my ReflectionUtil class:



public static class ReflectionUtil
{
    public static string GetMethodName(Expression<Action> action)
    {
        MethodCallExpression methodCallexpression = action.Body as MethodCallExpression;
        if (methodCallexpression != null)
            return methodCallexpression.Method.Name;
        return null;
    }
}

Hope that helps
This entry was posted in 15143, 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>