So I'm creating a messaging system. I'm currently on the 'Message list' page, I need it to display a list of all the conversations that the current user has. Currently, it displays all the messages that the user has sent and received as individual objects inside of an array. I need it to display only the most recent message that the user receives for each conversation with another user. In the example below, it should show only 2 conversations, because the senderUsername and recipientUsername are the same in 2 of the examples, but instead of doing that, it shows all of the messages, instead of the most recent one. The reason it is doing this is because of the way I've built the model. Is there any way of me getting it to do what I want it to do without changing the model
Model:
public class Messages
{
public int Id { get; set; }
public int SenderId { get; set; }
public int RecipientId { get; set; }
public string SenderUsername { get; set; }
public string RecipientUsername { get; set; }
public int ItemId { get; set; }
public string Message { get; set; }
public bool Read { get; set; }
public DateTime DateTimeSent { get; set; }
}
Code:
public IQueryable GetMessageList(string currentUsername)
{
var currentUser = _context.Users.FirstOrDefault(x => x.Username == currentUsername);
var currentUserId = currentUser.Id;
var messageList = _context.Messages.Where(x => x.SenderId == currentUserId || x.RecipientId == currentUserId).OrderByDescending(x => x.DateTimeSent);
return messageList;
}
Output:
[
{
"id": 4,
"senderId": 2,
"recipientId": 1,
"senderUsername": "dylan_costello_",
"recipientUsername": "jxchumber",
"itemId": 0,
"message": "MessagesForSendingDto.Message",
"read": false,
"dateTimeSent": "2020-05-07T17:47:04.5268228"
},
{
"id": 3,
"senderId": 1,
"recipientId": 2,
"senderUsername": "jxchumber",
"recipientUsername": "dylan_costello_",
"itemId": 0,
"message": "MessagesForSendingDto.Message",
"read": false,
"dateTimeSent": "2020-05-07T17:39:12.4228305"
},
{
"id": 2,
"senderId": 1,
"recipientId": 3,
"senderUsername": "jxchumber",
"recipientUsername": "pavster31",
"itemId": 0,
"message": "MessagesForSendingDto.Message",
"read": false,
"dateTimeSent": "2020-05-07T17:38:38.950303"
},
{
"id": 1,
"senderId": 1,
"recipientId": 3,
"senderUsername": "jxchumber",
"recipientUsername": "pavster31",
"itemId": 0,
"message": "MessagesForSendingDto.Message",
"read": true,
"dateTimeSent": "2020-05-07T17:31:25.3077606"
}
]