EF Core Loading Entities does not map to Query

.net-core c# entity-framework-core linq

Question

I'm writing an API for generically handling Rest. I'm having some trouble loading dependent entities. I'm using .Net-Core 2.0

I’m trying to grab out the last message for each conversation. I have a method for loading a list of conversations which looks like so:

[HttpGet("Convo")]
public async Task<Conversation[]> LoadConversation()
{
   var query = this._context.Conversations.OrderBy(x => x.Id);
   var messages = await query.Select(x => x.Messages.OrderBy(m =>
                                      m.Created).FirstOrDefault())
                             .ToArrayAsync();

   var conversations = await query.ToArrayAsync();

   return conversations;
}

When I check the messages I have a message whose has a conversation Id of 3011, When I check conversations, I have an Id Loaded of 3011. Yet, the conversation.Messages are still empty.

EDIT I've also tried to load them using an anonymous select, which still didn't map either

var convo = await query.Select(x => new { 
   Conversation = x, 
   Message = x.Messages.OrderBy(m => m.Created).FirstOrDefault() 
}).ToArrayAsync();

NOTE

If I include all of my messages, they map fine

var conversationWithAllMessages = await query.Include(x => x.Messages).ToArrayAsync();

They also work if I call SelectMany on the Entire collection

var messages = query.SelectMany(x => x.Messages)
                    .OrderBy(x => x.ConversationId)
                    .ToArray();

But I only only want to include the last message

EDIT

enter image description here

Why aren't my entities mapping, How Can I Get My Entities to map appropriately?

1
2
4/20/2018 12:21:05 AM

Accepted Answer

I think what is happening is that, EFCore expects a Collection Or IEnumerable To be able to map to the Collection Property of My Parent Entity

Looks like this is a bug with EF-Core. Maybe I'm overlooking the spec and only Collections should map to collections? As a work around I resolved this with SelectMany and Take.

var messages =  query.SelectMany(x => x.Messages.OrderBy(m => m.Created).Take(1))
                     .OrderBy(x => x.ConversationId)
                     .ToArray();
1
4/20/2018 12:35:51 AM

Popular Answer

You can force includes with this syntax

var query = this._context.Conversations.Include("Messages").OrderBy(x => x.Id);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow