Mergasov Mergasov - 1 year ago 114
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

How can I solve it?

Answer Source

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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download