Search code examples
c#linqgenericsexceptiondblinq

DbLinq generic extension method - string as keyselector?


The following snippet indicates what I want:

public static class DblinqExtension
{
    public static int MaxId<T>(this DbLinq.Data.Linq.Table<T> table) where T : class
    {
        var val = table.OrderByDescending(x => "Id").FirstOrDefault();
        return Convert.ToInt32(val);
    }
}

With DbMetal I've generated the mapping classes. Every table I have has the column Id (which is obviously an integer) and I want to know the MAX id.

Anyone any idea how I can get my snippet working??

Thanks!


I've found this article: OrderBy with a String keySelector

With that suggestion applied my code will become:

public static int MaxId<T>(this DbLinq.Data.Linq.Table<T> table) where T : class
{
    var val = table.OrderByDescending(CreateSelectorExpression<T>("Id")).FirstOrDefault();
    return Convert.ToInt32(val);
}

private static Expression<Func<T, Int32>> CreateSelectorExpression<T>(string propertyName) where T : class
{
    var parameterExpression = Expression.Parameter(typeof(T));
    return (Expression<Func<T, Int32>>)Expression.Lambda(
        Expression.PropertyOrField(parameterExpression, propertyName), 
        parameterExpression
    );
}

BUT now I get an error:

Value cannot be null. Parameter name: key


Solution

  • Alright, I've figured it out!!

        public static int MaxId<T>(this DbLinq.Data.Linq.Table<T> table) where T : class
        {
            var param = Expression.Parameter(typeof(T), "p");
            var body = Expression.PropertyOrField(param, "ID");
            var lambda = Expression.Lambda<Func<T, int>>(body, param);
    
            var val = table.OrderByDescending(lambda).FirstOrDefault();
            return Convert.ToInt32(val.GetType().GetProperty("ID").GetGetMethod().Invoke(val, null));
        }
    

    Thanks a lot @Yahia for your hint with the GetProperty part!