[英]How to get a list of user dialogs from the database of all messages using Entity Framework Core
I have a table in the database with messages, namely:我在数据库中有一个带有消息的表,即:
| Id | FromId | ToId | Text | Date | Read |
Here's what the class looks like:这是 class 的样子:
public class Message
{
public int Id { get; set; }
public IdentityUser From { get; set; }
public IdentityUser To { get; set; }
public string Text { get; set; }
public DateTime Date { get; set; }
public bool Read { get; set; }
}
I need to form a request to get a list of all the user's dialogs using the Entity Framework Core.我需要使用 Entity Framework Core 形成一个请求以获取所有用户对话框的列表。 I've sketched out a sample SQL query:
我已经勾勒出一个示例 SQL 查询:
SELECT FromId, MAX(Date) as updated_at, sum(Read) as new_messages
FROM (SELECT FromId, Date, Read
FROM Messages
WHERE ToId = 'f3578a36-208c-4504-8f3c-afa564455537'
UNION SELECT ToId, Date, 0
FROM Messages
WHERE FromId = 'f3578a36-208c-4504-8f3c-afa564455537'
ORDER BY Date DESC) as talks
GROUP BY FromId
ORDER BY Date DESC;
where `f3578a36-208c-4504-8f3c-afa564455537" is the Id of the user whose dialog list I want to get.其中“f3578a36-208c-4504-8f3c-afa564455537”是我想要获取其对话列表的用户的 ID。
However, I can't execute it using the Entity Framework (or don't know how).但是,我无法使用实体框架执行它(或者不知道如何)。 Is there any way to do this using only EF?
有没有办法只使用EF来做到这一点? I use SQLite.
我使用 SQLite。
Using EF I would write it down like this, I'd query separately for messages from and to user and group them appropriately:使用 EF 我会像这样写下来,我会分别查询来自和发往用户的消息并将它们适当地分组:
var chatsFromUser = dbContext.Messages
.Where(m => m.From.Id == "f3578a36-208c-4504-8f3c-afa564455537")
.GroupBy(m => m.To.Id);
var chatsToUser = dbContext.Messages
.Where(m => m.To.Id == "f3578a36-208c-4504-8f3c-afa564455537")
.GroupBy(m => m.From.Id);
But, I would also suggest that you should define ID
s properties for users in Message
entity class:但是,我还建议您在
Message
实体 class 中为用户定义ID
属性:
public class Message
{
public int Id { get; set; }
public IdentityUser From { get; set; }
// choose appropiate type, GUID maybe?
public string FromId { get; set; }
public IdentityUser To { get; set; }
// choose appropiate type, GUID maybe?
public string ToId { get; set; }
public string Text { get; set; }
public DateTime Date { get; set; }
public bool Read { get; set; }
}
Then query would be slightly simplified as you could access IDs directly from message object:然后查询会稍微简化,因为您可以直接从消息 object 访问 ID:
var chatsFromUser = dbContext.Messages
.Where(m => m.FromId == "f3578a36-208c-4504-8f3c-afa564455537")
.GroupBy(m => m.ToId);
var chatsToUser = dbContext.Messages
.Where(m => m.ToId == "f3578a36-208c-4504-8f3c-afa564455537")
.GroupBy(m => m.FromId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.