我需要从会话中获取(例如,2),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"
我可以通过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)时,不要限制我的列表。选择.....给我"子查询返回超过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行
答案 0 :(得分: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();