LINQ MAX空结果时给出异常

时间:2019-09-25 08:53:45

标签: c# linq

当前,以下语句给出错误。返回结果可以正常工作,但是在没有结果可用时会产生此异常

  

System.NotSupportedException:'指定的方法   类型上的'System.Nullable 1](System.Collections.Generic.IEnumerable 3,Nullable 3 ..., System.Func 1 [<> f__AnonymousType57 3 ... ,System.Nullable 2 [<> f__AnonymousType57 select top 1 * from ( select user_id, max(first_name) first_name, max(last_name) last_name, max(CONVERT(int,retired)) retired, count(user_id) ticket_count from table1 tb1 group by user_id) tb2 order by tb2.ticket_count asc 1 [System.Boolean]])'   'System.Linq.Enumerable'不能转换为LINQ to Entities   存储表达式,因为没有重载与传递的参数匹配。'

根据我的收集,它正在尝试模拟此SQL,该SQL选择票证数量最少的用户

var agentticketcountlist = (from tb1 in db.TABLE1 
   where tb1.GRP_ID == _ID  
   group new { tb1 } by tb1.USER_ID into g
   let first = g.FirstOrDefault()
select new
{
   USER_ID = g.Key ,
    FIRST_NAME = g.Max(x => x.tb1.FIRST_NAME),
    LAST_NAME = g.Max(x => x.tb1.LAST_NAME),
    RETIRED = g.Max(x =>x.tb1.RETIRED)  ,
    TICKET_COUNT = g.Count()
}).OrderBy(n => n.TICKET_COUNT).ToList();

if (agentticketcountlist.Count() > 0)
...
import pyspark.sql.functions as F

F.when((df.UPDAT_DT.cast("long") - df.CREAT_DT.cast("long")) >= 0,
                           df.UPDAT_DT).otherwise(df.CREAT_DT).alias('DT')

修改

我将语句简化为1个表,因为它连接了几个表。

但这是根据我给出的样本的一些样本数据(不要对我进行表标准化:))

SQL表数据类型。请注意位变成布尔值?在EF
中 USER_ID(nvarchar)
FIRST_NAME(nvarchar)
LAST_NAME(nvarchar)
退回(位)

123,简,母鹿,0
123,简,母鹿,0
234,约翰,母鹿,1

2 个答案:

答案 0 :(得分:0)

在最大值之前,如果未从查询中找到结果,则需要添加其默认值:

.DefaultIfEmpty(0).Max(x => x.value as int?) ?? 0DefaultIfEmpty()

答案 1 :(得分:0)

您没有提供任何示例数据,因此尚不清楚您的数据是什么样的。从错误消息中,据我了解,退休是布尔值,因此您真正追求的是对还是错:

var agentticketcountlist = (from tb1 in db.TABLE1 
   where tb1.GRP_ID == _ID  
   group tb1 by tb1.USER_ID into g
select new
{
    USER_ID = g.Key ,
    FIRST_NAME = g.Max(x => x.tb1.FIRST_NAME),
    LAST_NAME = g.Max(x => x.tb1.LAST_NAME),
    RETIRED = g.Any(x =>x.tb1.RETIRED),
    TICKET_COUNT = g.Count()
}).OrderBy(n => n.TICKET_COUNT).ToList();

编辑:

var agentticketcountlist = (from tb1 in db.TABLE1 
   where tb1.GRP_ID == _ID  
   group tb1 by tb1.USER_ID into g
select new
{
    USER_ID = g.Key ,
    FIRST_NAME = g.Max(x => x.FIRST_NAME),
    LAST_NAME = g.Max(x => x.LAST_NAME),
    RETIRED = g.Any(x =>x.RETIRED),
    TICKET_COUNT = g.Count()
}).OrderBy(n => n.TICKET_COUNT).ToList();