Mergasov Mergasov - 23 days ago 6
ASP.NET (C#) Question

EF Core: how to load a single item from collection-nav property?

I have one-to-many relationship between two entities: User (one) has Messages (many) collection.

There needs to display some information about User and at the same time needs to load single Message.
I try to do something like:

mycontext.Users.Where(..).Include(user => user.Messages.Take(1).First());


However this code throws ecxeption


InvalidOperationException: The property expression 'user=> {from
Message m in [chat].Messages select
[m] => Take(1) => First()}' is not valid. The expression should
represent a property access: 't => t.MyProperty'. For more information
on including related data, see
http://go.microsoft.com/fwlink/?LinkID=746393.


How can I solve it?

Answer

You cannot do that the way you have tried.You have to retrieve all the related messages from the db and after that filter it on the memory (IEnumerable) as shown below.

var useList= mycontext.Users.Where(..).Include(user => user.Messages);

 foreach (var u in useList)
  {

      var message= u.Messages.Take(1).First();

  }
Comments