Linq 可空对象必须有一个值。 .NET 6 和 EF Core 中的错误

Linq Nullable object must have a value. errors in .NET 6 and EF Core

我有这个代码:

IQueryable<WinnerClassExtend> dataList = 
from Class in _context.AllClass
join Winner in _context.AllWinners on Class.ClassId equals Winner.ClassId

let Extend = new { Winner, Class }
group Extend by Class.ClassId into Group

select new WinnerClassExtend
{
    Class = Group.Select(x => x.Class).FirstOrDefault(),
    NumberOfWinnerinClass = Group.Select(x => x.Winner).Count()
};

var count = dataList.Count();

我尝试获取 IQueryable 的计数,就像我在 .net Framework 和 entity framework 中所做的那样,但它似乎不起作用...我收到错误

Nullable object must have a value

我不知道它有什么问题,我也尝试使用它,

IQueryable<WinnerClassExtend> dataList =
     _context.AllClass
    .Join(_context.AllWinners , Class => Class.ClassId, Winner => Winner.ClassId, (Class, Winner) => new { Class, Winner })
    .GroupBy(x => new { x.Class.ClassId })
    .Select(x => new WinnerClassExtend
    {
        Class = x.Select(i => i.Class).FirstOrDefault(),
        NumberOfWinnerinClass = x.Select(i => i.Winner).Count()
    });

var count = dataList.Count();

它 returns 一样...

我已经阅读了这个错误的一些问题,但它似乎与同一个问题不同,有人可以帮忙吗?

尝试以下查询:

var dataList = 
    from Class in _context.AllClass
    select new WinnerClassExtend
    {
        Class = Class,
        NumberOfWinnerinClass = _context.AllWinners.Where(w => w.ClassId == Class.ClassId).Count()
    };

var count = dataList.Count();

或另一个:

var grouped = 
    from Winner in _context.AllWinners
    group Winner by Class.ClassId into Group
    select new 
    {
        ClassId = Group.Key,
        NumberOfWinnerinClass = Group.Count()
    };

var dataList = 
    from Class in _context.AllClass
    join g in grouped on ClassId.ClassId equals g.ClassId
    select new WinnerClassExtend
    {
        Class = Class,
        NumberOfWinnerinClass = g.NumberOfWinnerinClass
    };

var count = dataList.Count();

在这两种情况下比较执行计划。

在我看来你需要一个左外连接:

var dataList =
    from c in _context.AllClass
    join w in _context.AllWinners on c.ClassId equals w.ClassId into winners
    select new WinnerClassExtend
    {
        Class = c,
        NumberOfWinnerinClass = winners.Count()
    };

var count = dataList.Count();