Linq使用聚合查询表没有记录报错

摘要 : Linq query table does not record using the aggregate error

Linq 聚合查询 遇到空表 怎么处理,.Max(p => p.IOrder); 没有记录报错,

var query= db.MenuInfo.Where(p => p.PID == PID);
if(query.Any())
{
  double q = query.Max(p => p.IOrder);
  ......
}
else
{
  ......
}

即使你写T-SQL,也得写:

if exists(select * from MenuInfo where pid=@pid)
  select max(pid) from MenuInfo
else
  select ......

总之是要两步才可能得到结果的。

方法1
int? maxValue=null;
var items=from c in context.table1 select c;
try
{
  maxValue=items.Max(p=>p.column_1)
}
catch(InvalidOperationException){}
if(maxValue.HasValue){}
else{}
方法2
int? maxValue = null;
var items=from c in context.table1 select c;
if(items.Count())maxValue=maxValue=items.Max(p=>p.column_1)
if(maxValue.HasValue){}
else{}

发现一个更好的做法

int? col;
var items=from c in context.table1
          select c;
int? maxValue=items.Max(p=>col = p.column_1);

select max(pid) from MenuInfo

当没有记录时,返回的不是空记录,而是字段值为NULL(数据库值)的记录,并不是空记录。
null 转换成int 就会出错。
上一篇 :Visual Studio切换设计视图无响应
下一篇 :安装SQLServer失败报一般性网络错误