Registered User
Registered User

Reputation: 3699

Return a List with multiple results using LINQ and EF

I have this simple method that returns a user:

User usr = ReliableExecution.RetryWithExpression<User, User>(u => u.FirstOrDefault(x => x.UserEmail == userEmail));

Now I need to create a similar method, but I need to return a list

List<Asset> lst = ReliableExecution.RetryWithExpression<Asset, List<Asset>>(u => u.SelectMany(x => x.EventId == eventId));

My problem is with the [SelectMany(x => x.EventId == eventId)] part that doesn't compile and I can't understand exactly how to use LINQ to get multiple results. I have specified "SelectMany" just for an example, it can be whatever you find correct.

This is the signature of RetryWithExpression for reference:

   public static TValue RetryWithExpression<T, TValue>(Func<ObjectSet<T>, TValue> func, Int32 retryInfiniteLoopGuard = 0)
         where T : class

Upvotes: 1

Views: 414

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

I think your expression should be rewritten as follows:

List<Asset> lst = ReliableExecution
    .RetryWithExpression<Asset, List<Asset>>(
        u => u.Where(x => x.EventId == eventId).ToList()
    );

In simple terms, SelectMany flattens a "list of lists of items A" into a "list of items B" using a functor that extracts a list of items B from each single item A; this is not what you want to do.

Upvotes: 1

yamen
yamen

Reputation: 15618

It seems like you want:

List<Asset> lst = ReliableExecution.RetryWithExpression<Asset, List<Asset>>
                  (u => u.SelectMany(x => x.Where(y => y.EventId == eventId)));

SelectMany expects the passed Func to return an IEnumerable, which it then flattens. You were passing through a list of Asset and then trying to select the EventId directly on the list. What you really wanted was to select all Assets in the list with matching EventId, hence the extra Where clause.

Upvotes: 1

Related Questions