解决Linq Join Group by 时报错:Nullable object must have a value.
Linq Join Group by 时报Nullable object must have a value.
例如:
from s in subject on ch.SubId equals s.SubId
join gc in (from aq in question
group aq by aq.ChapterId
into gaq
select new
{
Id = gaq.Key,
Count = gaq.Count(),
})
on s.QueId equals gc.Id
into gc2
from gc in gc2.DefaultIfEmpty()
结果将会报错
生成的sql语句符合预期,为简单的join
解决方法:
/// <summary>
/// 解决问题: efcore group new dynamic对象时生成int 型而不是 int? 而导致 Nullable object must have a value.的问题
/// </summary>
public class GroupTableViewModel
{
/// <summary>
/// Key
/// </summary>
public int? Id { get; set; }
/// <summary>
/// Count
/// </summary>
public int? Count { get; set; }
/// <summary>
/// Sum
/// </summary>
public int? Sum { get; set; }
public int? Max { get; set; }
}
加上 GroupTableViewModel 问题解决
from s in subject on ch.SubId equals s.SubId
join gc in (from aq in question
group aq by aq.ChapterId
into gaq
select new GroupTableViewModel
{
Id = gaq.Key,
Count = gaq.Count(),
})
on s.QueId equals gc.Id
into gc2
from gc in gc2.DefaultIfEmpty()
解决Join 多值报错
from employee in employees
join student in students
on new { employee.FirstName, employee.LastName } equals new { student.FirstName, student.LastName }
select employee.FirstName + " " + employee.LastName;
例如
from u in User
join sac in (from sa in Answer
join e in Exam on sa.ExamId equals e.ExamId
group sa by new { UserId = sa.UserId, ExamId = sa.ExamId, }
into gsa
select new
{
UserId = gsa.Key.UserId,
ExamId = gsa.Key.ExamId,
ScoreCount = gsa.Sum(x => x.Score),
})
on new { UserId = u.UserId, ExamId = ue.ExamId } equals new { UserId = sac.UserId, ExamId = sac.ExamId }
into sac2
from sac in sac2.DefaultIfEmpty()
生成sql语句正常 但报错 Nullable object must have a value.
解决方法:
public class GroupExam
{
public int? UserId { get; set; }
public int? ExamId { get; set; }
public decimal? ShortAnswerScoreCount { get; set; }
}
将原linq修改为
from u in User
join sac in (from sa in Answer
join e in Exam on sa.ExamId equals e.ExamId
group sa by new { UserId = sa.UserId, ExamId = sa.ExamId, }
into gsa
select new GroupExam
{
UserId = gsa.Key.UserId,
ExamId = gsa.Key.ExamId,
ScoreCount = gsa.Sum(x => x.Score),
})
on new { UserId = u.UserId, ExamId = ue.ExamId } equals new { UserId = (int)sac.UserId, ExamId = sac.ExamId }
into sac2
from sac in sac2.DefaultIfEmpty()
问题解决
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!