gpt4 book ai didi

c# - 在 Entity Framework 中的 Groupby 中获取(限制)列表

转载 作者:行者123 更新时间:2023-11-29 02:44:01 25 4
gpt4 key购买 nike

我需要从对话中获取(例如,2)条消息

我不在乎我的列表是什么样子,但我只想要来自 id 1 的 2 条消息,来自 id2 的 2 条消息,然后继续

例子:

id = idConversation

Id | MessageId | Message
---|-----------|--------
1 | 1 | "asd"
1 | 2 | "asd2"
1 | 3 | "asd3"
1 | 4 | "asd4"
2 | 5 | "asd5"
3 | 6 | "asd6"
3 | 7 | "asd7"
3 | 8 | "asd8"
3 | 9 | "asd9"
3 | 10 | "asd10"
4 | 11 | "asd11"
4 | 12 | "asd12"
4 | 13 | "asd13"

我想要那个

Id   MessageId   Message
---|-----------|--------
1 | 1 | "asd"
1 | 2 | "asd2"
2 | 5 | "asd5"
3 | 6 | "asd6"
3 | 7 | "asd7"
4 | 11 | "asd11"
4 | 12 | "asd12"

我可以使用 grouby idConversation,但我无法在对话中使用 grouby 来限制数量。

var test = unitOfWork.ChatMensagemRepository.GetAll()
.Where(x => x.PessoaCodigoPessoa == codigoRemetente)
.GroupBy(x => x.ChatConversaCodigoChatConversa)
.Select(group => new
{
codigoChat = group.Key,
list = group.Select(mensagem => new
{
// do stuff
})
}).ToList();

这没问题...但不要限制我的列表,当我执行 group.take(2).Select..... 给我“子查询返回超过 1 行”

var test = unitOfWork.ChatMensagemRepository.GetAll()
.Where(x => x.PessoaCodigoPessoa == codigoRemetente)
.GroupBy(x => x.ChatConversaCodigoChatConversa)
.Select(group => new
{
codigoChat = group.Key,
list = group.Take(2).Select(mensagem => new
{
// do stuff
})
}).ToList();

错误:子查询返回多于 1 行

var test = unitOfWork.ChatMensagemRepository.GetAll()
.Where(x => x.PessoaCodigoPessoa == codigoRemetente)
.GroupBy(x => x.ChatConversaCodigoChatConversa)
.Select(group => new
{
codigoChat = group.Key,
list = group.Select(mensagem => new
{
// do stuff
}).take(2)
}).ToList();

错误:子查询返回多于 1 行

最佳答案

这是因为 MySQL 的 EF 提供程序或服务器本身无法将此 linq 转换为 SQL,因此您应该首先从服务器获取数据,然后才将其与 Take(2) 分组:

var test = unitOfWork.ChatMensagemRepository.GetAll()
.Where(x => x.PessoaCodigoPessoa == codigoRemetente)
//this section is added
.Select(x => new
{
x.ChatConversaCodigoChatConversa,
x.prop1,//specify only columns, which you need for below code with Take
x.prop2
}).ToList()
//end of section
.GroupBy(x => x.ChatConversaCodigoChatConversa)
.Select(group => new
{
codigoChat = group.Key,
list = group.Take(2).Select(mensagem => new
{
mensagem.prop1,
mensagem.prop2
}).ToList()
}).ToList();

关于c# - 在 Entity Framework 中的 Groupby 中获取(限制)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45837750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com