Ilya Loskutov
Ilya Loskutov

Reputation: 2201

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?

Upvotes: 1

Views: 808

Answers (2)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Pretty easy. Instead of trying to load a message from a user, load the user from the message:

mycontext.Messages.Where(..).Include(msg => msg.User);

In fact, you can do it easier for you:

mycontext.Messages
.Include(msg => msg.User)
.Where(msg => msg.User...);

So you don't have to filter on Message rather than on User

Upvotes: 2

Sampath
Sampath

Reputation: 65870

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

  }

Upvotes: 0

Related Questions