Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ICollection doesn't show up on ASP.NET core web api get request

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading