I have 2 models for a chat system like the following
a chat message model :
public partial class ChatMessage : BaseEntity
{
[ForeignKey("ChatThread")]
public long ChatThreadID { get; set; }
public string Sender { get; set; }
public string Message { get; set; }
}
and a chat thread model :
public partial class ChatThread : BaseEntity
{
public string User1 { get; set; }
public string User2 { get; set; }
[ForeignKey("ChatThreadID")]
public ICollection<ChatMessage> ChatMessages { get; set; }
}
I’m doing a simple get request like this to get all the chat threads :
// GET: api/Chat
[HttpGet]
public async Task<ActionResult<IEnumerable<ChatThread>>> GetThreads()
{
var threads = _context.ChatThreads.Where(thread => thread.User1 == UserId || thread.User2 == UserId);
return await threads.ToListAsync();
}
but the response I’m getting is this although I’m 100% sure that the chat thread has Chat messages in it
[
{
"user1": "2",
"user2": "1",
"chatMessages": null,
"id": 1
}
]
the chatMessages list is always null in the response, I’m fairly new to asp.net, Am I doing the request wrong ?
>Solution :
Relationships won’t be loaded automatically, you need to include them.
[HttpGet]
public async Task<ActionResult<IEnumerable<ChatThread>>> GetThreads()
{
var threads = _context.ChatThreads.Where(thread => thread.User1 == UserId || thread.User2 == UserId).Include(t => t.ChatMessages);
return await threads.ToListAsync();
}
Unlike EF6, EF core disables lazy loading by default.
You can find more detailsin the documentation.