Registered User
Registered User

Reputation: 3699

Fetching related object using LINQ and EF

I have two objects that are linked by a foreign key relationship and I use DataModel to map the objects:

Event:1------*:Asset

I wrote a query that fetches all assets for a given [eventPublicId]

List<Asset> assetList =
    ReliableExecution.RetryWithExpression<Event, List<Asset>>
    (u => u.FirstOrDefault(x => x.PublicId == eventPublicId).Assets.ToList()).ToList();

My problem is that I had to call ToList() twice and this looks awkward. Also I had to use FirstOrDefault, but when I tried to use [Where] or anything else, it didn't compile.

Is there any other better way how this code can be rewritten?

This is RetryWithExpression signature for reference:

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

Upvotes: 0

Views: 179

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109080

You specify that the func parameter should return a List<Asset>, so the navigation property event.Assets does not fit the bill: It is an EntityCollection<Asset>, which is not implicitly convertible to the delegate return type. The explicit conversion ToList() creates the specified type.

Technically, to get rid of the ToList, you should use

ReliableExecution.RetryWithExpression<Event, EntityCollection<Asset>> ...

but I don't know if that meets your functional requirements.

Upvotes: 1

Related Questions