データ テーブルに対するカスタム クエリを作成するために、C# Dynamic Linq ライブラリを使用しています。私が抱えている問題は、null を持つフィールドで集計操作を実行しようとすると、エラーが発生することです。
次のようなクエリを実行しようとしています。
var query = myDataTable.AsEnumerable().AsQueryable();
var newquery = query.GroupBy("new (get_item(@0).ToString() AS Forename)", "it", groupList.ToArray());
newquery = newquery.Select("new (it.Key.Tier.ToString() as Tier, @0(it) as SumTotal", funcs.ToArray());
合計している列に Null 値がある場合、「DBNull.Value を 'System.Double' 型にキャストできません。null 許容型を使用してください。」というエラーが表示されます。
funcs 配列には、Sum 関数を実行するためのラムダ式が含まれています。以下の関数を呼び出すことでビルドされます。
public LambdaExpression GetGroupByLambdaExpression(Type groupByKeyType, string columnName, Type columnType, string expType)
{
ConstantExpression colParam = Expression.Constant(columnName, typeof(string));
MethodInfo fieldMethod = typeof(DataRowExtensions).GetMethod("Field", new Type[] {typeof(DataRow), typeof(string)});
fieldMethod = fieldMethod.MakeGenericMethod(columnType);
ParameterExpression rowParam = Expression.Parameter(typeof(DataRow), "r");
MethodCallExpression fieldMethodCall = Expression.Call(fieldMethod, rowParam, colParam);
dynamic columnExpression = Expression.Lambda(fieldMethodCall, rowParam);
MethodInfo sumMethod = null;
if (expType == "Count")
{
//Count will return 2 methods, we only want the first one with 1 parameter
sumMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == expType & m.ReturnType.Equals(columnType) & m.IsGenericMethod & m.GetParameters().Count() == 1);
}
else if (expType == "Average")
{
//Average has multiple overrides so just use the first one
if (columnType == typeof(Int16) || columnType == typeof(Int32) || columnType == typeof(Int64))
{
sumMethod = typeof(Enumerable).GetMethods().First(m => m.Name == expType & m.ReturnType.Equals(typeof(double)) & m.IsGenericMethod);
}
else
{
sumMethod = typeof(Enumerable).GetMethods().First(m => m.Name == expType & m.ReturnType.Equals(columnType) & m.IsGenericMethod);
}
}
else
{
sumMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == expType & m.ReturnType.Equals(columnType) & m.IsGenericMethod);
}
sumMethod = sumMethod.MakeGenericMethod(typeof(DataRow));
ParameterExpression groupParam = Expression.Parameter(groupByKeyType, "g");
MethodCallExpression sumMethodCall = null;
if (expType == "Count")
{
sumMethodCall = Expression.Call(sumMethod, groupParam);
}
else
{
sumMethodCall = Expression.Call(sumMethod, groupParam, columnExpression);
}
dynamic sumALambda = Expression.Lambda(sumMethodCall, groupParam);
return sumALambda;
}
データテーブルで DbNull 値を処理する方法を知っている人はいますか? 私は完全に困惑しています