Reputation: 83
I'm using a dynamic linq on the DataTable to generate consolidated summations. All everything works great except when a value is null for Column9 used for summation. I got NullException ''Object cannot be cast from DBNull to other types.''. All these columns are dynamically selected by users, including the column for sum.
public bool CreateConsolidation(string sum_Column) // e.g. Column9 will pass as sum_Column
{
var sum_str = "Sum(Convert.ToInt32(" + sum_Column + ")) as " + sum_Column;
var double_grouping = (dt_excel.AsEnumerable().AsQueryable()
.GroupBy("new (it.Column4, it.Column5, it.Column6, it.Column7, it.Column11 )", "it"))
.Select("new (Key.Column4 as Column4, Key.Column5 as Column5, Key.Column6 as Column6, Key.Column7 as Column7, Key.Column11 as Column11, Sum(new ( " + sum_str + " )) as QTY )").ToDynamicList();
//have to perform some other operations based on above result
return true;
}
Is there any way to check this null value for this dynamic linq Query?
And I want the result is something like below. the first line must check the DBNull Value.
public bool CreateConsolidation(string sum_Column) // e.g. Column9 will pass as sum_Column
{
var sum_str = "Sum(it." + sum_Column + " == DBNull.Value ? : Convert.ToInt32(it." + sum_Column + ")) as " + sum_Column;
var double_grouping = (dt_excel.AsEnumerable().AsQueryable()
.GroupBy("new (it.Column4, it.Column5, it.Column6, it.Column7, it.Column11 )", "it"))
.Select("new (Key.Column4 as Column4, Key.Column5 as Column5, Key.Column6 as Column6, Key.Column7 as Column7, Key.Column11 as Column11, Sum(new ( " + sum_str + " )) as QTY )").ToDynamicList();
//have to perform some other operations based on above result
return true;
}
Upvotes: 0
Views: 52