DbLinq 通用扩展方法 - 字符串作为键选择器?
以下代码片段表明了我想要的内容:
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);
}
}
通过 DbMetal,我生成了映射类。我的每个表都有 Id 列(这显然是一个整数),我想知道 MAX id。
有人知道我如何让我的代码片段工作吗?
谢谢!
我找到了这篇文章:OrderBy with a String keySelector< /a>
应用该建议后,我的代码将变为:
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
);
}
但现在我收到错误:
值不能为空。参数名称:key
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定,但尝试
编辑 - 如果您需要将 Id 作为字符串放入表达式中:
编辑 - 如果您需要拆分:
编辑 - 如果“Id”是一个字段,那么您需要这个:
not sure but try
EDIT - if you need to take Id as string into the expression:
EDIT - if you need to split up:
EDIT - if "Id" is a field then you need this:
好吧,我已经弄清楚了!!
非常感谢@Yahia 对 GetProperty 部分的提示!
Alright, I've figured it out!!
Thanks a lot @Yahia for your hint with the GetProperty part!