C# Expression - Getdefault Value or convert int? to int

479 Views Asked by At

I have a Class like below

public class GrouppedStockGift
{
    public DateTime? TimeCreated { get; set; }
    public int? StoreID { get; set; }
    public int? UserCreated { get; set; }
    public int? WorksID { get; set; }
    public int? WorkOrderCode { get; set; }
    public decimal? GiftPrice { get; set; }
    public decimal? GiftMoney { get; set; }
    public int SaleCount { get; set; }
}

I have Create a dynamic expression builder, in some case i need to convert int? to int or getdefaultvalue of int for example

var sumMethodint = typeof(Enumerable).GetMethods()
                       .Single(x => x.Name == "Sum"
                                 && x.GetParameters().Count() == 2
                                 && x.GetParameters()[1]
                                     .ParameterType
                                     .GetGenericArguments()[1] == typeof(int?));
sumMethodint = sumMethodint.MakeGenericMethod(typeof(GrouppedStockGift));
Expression<Func<GrouppedStockGift, int?>> SaleCount = y => y.SaleCount;
var SaleCountExtractor = Expression.Call(sumMethodint, parameter, SaleCount);
bindings.Add(
              Expression.Bind(
                           typeof(GrouppedStockGift).GetProperty("SaleCount"),
                           SaleCountExtractor));

but when execute last row Exception returned around type mismached
because SaleCount is int but sum method return int?
can any one help me?

2

There are 2 best solutions below

0
On BEST ANSWER

You must just change Expression.Call row to

var SaleCountExtractor = Expression.Call(Expression.Call(sumMethodint, parameter, SaleCount), "GetValueOrDefault", Type.EmptyTypes);

in the above code

Expression.Call(exp, "GetValueOrDefault", Type.EmptyTypes);

get default value of int

0
On

I assume that problem is in your decision to use the overload of Sum which returns int?. You should use the another overload which gets selecotr of type Func<T, int> and returns int.

var parameter = Expression.Parameter(typeof (IEnumerable<GrouppedStockGift>));
var sumMethodint = typeof(Enumerable).GetMethods()
            .Single(x => x.Name == "Sum"
                        && x.GetParameters().Count() == 2
                        && x.GetParameters()[1]
                            .ParameterType
                            .GetGenericArguments()[1] == typeof(int));
sumMethodint = sumMethodint.MakeGenericMethod(typeof(GrouppedStockGift));
Expression<Func<GrouppedStockGift, int>> saleCount = y => y.SaleCount;
var saleCountExtractor = Expression.Call(sumMethodint, parameter, saleCount);

bindings.Add(Expression.Bind(typeof(GrouppedStockGift).GetProperty("SaleCount"),
                             saleCountExtractor));