连表查询 group by 出现异常Nullable object must have a value
原因:两表进行左连接时,以左表为基表,右表为外表,当右表有数据满足查询条件时则跟左表关联,不满足时将以左表字段为主,右表字段值为空,这样一来,尽管数据库里数值类型的字段设置了默认值为0,还是会因为左连查询而被置空。
所以在查询时就有了空值被赋给数值类型字段,即导致Nullable object must have value 该错误的发生。
解决方案:
方式一:针对左表分组的匿名对象new一个具体的对象并将值类型的字段设置为可空
出错语句:
var queryC = from d in queryD group d by d.PicId into g select new { PicId= g.Key, Count = g.Count() }; var query = from r in queryR join c in queryC on r.FId equals c.PicId into g from cg in g.DefaultIfEmpty() join s in _repository.GetAll() on r.FId equals s.PicId into k from sk in k.DefaultIfEmpty() select new RecordDto() { Type = r.Type, Name = r.Name, FId = r.FId, Id = r.Id, Status = sk != null ? sk.Status : false, Type = cg != null ? TypeEnum.多 : TypeEnum.单 };
增加对象ResultGroup,并将值类型的Count设置为可空
修改后linq语句
var queryC = from d in queryD
group d by d.PicId into g
select new ResultGroup()
{
PicId= g.Key,
Count = g.Count()
};
var query = from r in queryR
join c in queryC on r.FId equals c.PicId into g
from cg in g.DefaultIfEmpty()
join s in _repository.GetAll() on r.FId equals s.PicId into k
from sk in k.DefaultIfEmpty()
select new RecordDto()
{
Type = r.Type,
Name = r.Name,
FId = r.FId,
Id = r.Id,
Status = sk != null ? sk.Status : false,
Type = cg != null ? TypeEnum.多 : TypeEnum.单,
Count = cg.Count > 0? cg.Count : 0
};
方式二:直接判断值类型的结果后赋值
var queryC = from d in queryD group d by d.PicId into g select new { PicId= g.Key, Count = g.Count() }; var query = from r in queryR join c in queryC on r.FId equals c.PicId into g from cg in g.DefaultIfEmpty() join s in _repository.GetAll() on r.FId equals s.PicId into k from sk in k.DefaultIfEmpty() select new RecordDto() { Type = r.Type, Name = r.Name, FId = r.FId, Id = r.Id, Status = sk != null ? sk.Status : false, Type = cg.Count > 0 ? TypeEnum.多 : TypeEnum.单,
Count = cg.Count > 0 ? cg.Count : 0
};