开发者

DbLinq generic extension method - string as keyselector?

开发者 https://www.devze.com 2023-03-22 00:29 出处:网络
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

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


not sure but try

var Result = from x in table select x.Max ( x => x.Id );

EDIT - if you need to take Id as string into the expression:

var Result = from x in table select x.Max ( x => x.GetType().GetProperty ("Id").GetGetMethod().Invoke (x, null) );

EDIT - if you need to split up:

var Result1 = from x in table select x; var Result2 = Result1.Max(x => x.GetType().GetProperty("Id").GetGetMethod().Invoke(x, null)); 

EDIT - if "Id" is a field then you need this:

var Result1 = from x in table select x; 
var Result2 = Result1.Max(x => x.GetType().GetField ( "Id" ).GetValue(x));


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消