IQueryable<T> OrderBy<T> Extension Fails with Foreign Key Property

414 views Asked by At

This is the MyPageViewModel:

public class MyPageViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string DealerSource { get; set;}

    public override void CreateMapping()
    {
        Mapper.CreateMap<MyPage, MyPageViewModel>().
        ForMember(dest => dest.DealerSource,opt => opt.MapFrom(w => w.DealerSource.Value));
    }
 }

This is MyPage entity:

[Table("MyPage")]
public partial class MyPage
{
    public Guid Id { get; set; }
    public Guid DealerId { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public virtual Dealer DealerSource { get; set; }
}

And, this is the Dealer entity:

[Table("Dealer")]
public partial class Dealer
{
    public Guid Id { get; set; } 
    public string Value { get; set; }
}

Relationship between MyPage and Dealer is, Dealer can have many MyPages.

MyPageViewModel is displayed in a grid which is sortable for Id, Name and Surname columns.

This is the OrderBy<T> extension method for IQueryable<T>:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortProperty, ListSortDirection sortOrder)
{
    var type = typeof(T);
    var property = type.GetProperty(sortProperty);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var orderByExp = Expression.Lambda(propertyAccess, parameter);
    var typeArguments = new Type[] { type, property.PropertyType };
    var methodName = sortOrder == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
    var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp));
    return source.Provider.CreateQuery<T>(resultExp);
}

The problem is with the DealerSource column. It's not possible to sort the grid by that. As it is foreign key, second line of OrderBy method type.GetProperty(sortProperty) returns null. I've come unstuck to find a workaround.

0

There are 0 answers