LINQ to Entities Union正在抛出错误

Ela*_*esh 9 c# linq linq-to-entities entity-framework

我设法让以下工作:

var transactions = from t in context.Transactions
                   group t.Create_Date_Time by t.Participation_Id
                       into t1
                   select new { ParticipationId = t1.Key, CreateDateTime = t1.Max() };

var cases = from c in context.Cases
            group c.Create_Date_Time by c.Participation_Id
                into c1
            select new { ParticipationId = c1.Key, CreateDateTime = c1.Max() };

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 : i.Create_Date_Time
                       by pp.Participation_Id
                       into i1
                   select new { ParticipationId = i1.Key, CreateDateTime = i1.Max() };

transactions.Union(cases);
Run Code Online (Sandbox Code Playgroud)

但是当我试图添加第三个输出时,

transactions.Union(interactions);
// or
interactions.Union(transactions);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

两种方式都抛出以下错误

错误1实例参数:无法从'System.Collections.Generic.List <AnonymousType#1>'转换为'System.Linq.IQueryable <AnonymousType#2>'
错误2'System.Collections.Generic.List <AnonymousType#1> '不包含'Union'的定义和最佳扩展方法重载'System.Linq.Queryable.Union <TSource>(System.Linq.IQueryable <TSource>,System.Collections.Generic.IEnumerable <TSource>)'一些无效的论点

第三个序列的唯一区别是,我正在使用另一个表的连接.我试过了.AsEnumerable(),.ToList()而且.ToArray(),他们都没有帮助.

dic*_*d30 8

在创建时interactions,其类型不是int和DateTime的匿名类型,它是int和可为空的 DateTime.这是因为在你的内联if语句中,你永远不会调用.Value可空列.如果您创建interactions这样的代码,您的代码应该有效:

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()};
Run Code Online (Sandbox Code Playgroud)

更简单的例子:

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
Run Code Online (Sandbox Code Playgroud)

尽管我们可以很容易地看到内联if语句在任何一种情况下都不会返回空值,但编译器无法做出这样的保证,并且必须在第二种情况下键入返回值为可空int的返回值.