LINQ to Entities Union is throwing an error

后端 未结 2 863
终归单人心
终归单人心 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:45

    Most likely t1.Key and i1.Key are different types. The anonymous types must have exactly the same property names and types, declared in the same order for you to be able to union them.

    As a side note, you probably also want to change this line of your code:

    transactions.Union(cases);
    

    to this:

    var unionedQuery = transactions.Union(cases);
    

    otherwise it won't perform the union, because you've not stored the resulting query.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题