问题描述
我需要从对话中获取(例如2条)2条消息
I need to take (for example, 2), 2 messages from a conversation
我不在乎列表的样子,但是我只想从id 1发送2条消息,从id2发出2条消息,然后继续
I dont care about how my list looks like, but i want only 2 messages from id 1, 2 messages from id2, and go on
示例:
id = idConversation
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限制数量.
i can grouby idConversation, but i cant limit quantity using grouby in a conversation.
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行"
this is ok... but dont limit my list, when i do group.take(2).Select..... give me "Subquery returns more than 1 row"
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行
error : Subquery returns more than 1 row
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行
error : Subquery returns more than 1 row
推荐答案
原因是因为用于MySQL的EF提供程序或服务器本身无法将此linq转换为SQL,所以您首先应该从服务器获取数据,然后才能用Take(2)
将其分组:
It is caused, because EF provider for MySQL or server itself can't translate this linq to SQL, so you should at first get data from server and only then group it with 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();
这篇关于实体框架中Groupby内的Take(limit)列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!