如何按 Linq 语句分组

本文关键字:语句 Linq 何按 | 更新日期: 2023-09-27 18:36:12

如何按此 linq 语句进行分组?

public IQueryable<Lottery> GetLotteriesByLotteryOfferId(int lotteryOfferId)
{
    return this.db.LotteryOffers
                                .Where(lo => lo.Id == lotteryOfferId)
                                .SelectMany(lo => lo.LotteryDrawDates)
                                .Select(ldd => ldd.Lottery);                                        
}

这不起作用:

public IQueryable<Lottery> GetLotteriesByLotteryOfferId(int lotteryOfferId)
{
    return this.db.LotteryOffers
                                .Where(lo => lo.Id == lotteryOfferId)
                                .SelectMany(lo => lo.LotteryDrawDates)
                                .Select(ldd => ldd.Lottery)
                                .GroupBy(s => new { s.Name, s.CreatedBy, s.ModifiedOn, s.Id })
                                .Select(g => new Lottery
                                                {
                                                    Name = g.Key.Name,
                                                    CreatedBy = g.Key.CreatedBy,
                                                    ModifiedOn = g.Key.ModifiedOn,
                                                    Id = g.Key.Id
                                                });
}

我收到的错误:

实体或复杂类型"彩票"不能在 LINQ 中构造 到实体查询。

我使用数据服务(网络服务)。

如何按 Linq 语句分组

LINQ to SQL 和 LINQ to Entities(与 LINQ to

Objects 和 LINQ to Xml 不同)使用高阶方法来生成将在数据库上运行的 SQL,因此 lambda 不具备该语言的全部功能。在Select"子句"中创建新Lottery是没有意义的 - 您不想在数据库进程中创建这些Lottery对象,而是希望在应用程序进程中创建它们。

您需要做的是使用AsEnumerable

 return this.db.LotteryOffers
                            .Where(lo => lo.Id == lotteryOfferId)
                            .SelectMany(lo => lo.LotteryDrawDates)
                            .Select(ldd => ldd.Lottery)
                            .GroupBy(s => new { s.Name, s.CreatedBy, s.ModifiedOn, s.Id })
                            .AsEnumerable()
                            .Select(g => new Lottery
                                            {
                                                Name = g.Key.Name,
                                                CreatedBy = g.Key.CreatedBy,
                                                ModifiedOn = g.Key.ModifiedOn,
                                                Id = g.Key.Id
                                            });

AsEnumerable之前的所有内容都会生成 SQL。对 AsEnumerable 的调用强制 C# 执行查询并以对象流的形式获取结果 - Select现在可以使用该对象来生成Lottery对象。