LINQ to Entities Union is throwing an error

后端 未结 2 864
终归单人心
终归单人心 2021-01-12 00:00

I have managed to get the following working:

var transactions = from t in context.Transactions
                   group t.Create_Date_Time by t.Participation         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 00:54

    When you create interactions, its type is not an anonymous type of int and DateTime, it is of int and nullable DateTime. This is because in your inline if statement, you never call .Value off of the nullable column. Your code should work if you create interactions like this:

    var interactions = from i in context.Interactions
                       join pp in context.Party_Participation on i.Party_Id equals pp.Party_Id
                       group i.Last_Update_Date_Time.HasValue ? i.Last_Update_Date_Time.Value : i.Create_Date_Time by
                           pp.Participation_Id
                       into i1
                       select new {ParticipationId = i1.Key, CreateDateTime = i1.Max()};
    

    Simpler Example:

    var lst = new int?[] { 2,3,null,5,5 };
    var lst2 = new int[] { 2,3,4,5,6 };
    
    lst.Select(x => x.HasValue ? x.Value : 0).Union(lst2); //works fine
    lst.Select(x => x.HasValue ? x : 0).Union(lst2); //throws error
    lst.Select(x => x ?? 0).Union(lst2); //also works
    

    Even though we can easily see that the inline if statement will never return a null value in either case, the compiler cannot make such guarantees and has to type the return value to that of a nullable int in the second case.

提交回复
热议问题