Jimmyt1988
Jimmyt1988

Reputation: 21126

Select related entity from query rather than the main entity

This is a query to favourite fields

public IEnumerable<Field> GetAllFavouriteFieldsRelatedToUser(
    int page, 
    int amount, 
    string sort, 
    string order, 
    ISearchCriteria searchCriteria, 
    string userID)
{
    return context.FavouriteFields
                  .Select( x => x.Field )
                  .Where( x => x.CreatedBy.Id == userID )
                  .Skip( ( page - 1 ) * amount )
                  .Take( amount );
}

I want it to return the field it is actually related to, rather than the favourite field entity... thus the Select query. However, this does not work.

How do I go about achieving this?

Upvotes: 1

Views: 45

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You must put Select last or after Where based on your requirements:

context.FavouriteFields
    .Where(x => x.CreatedBy.Id == userID) // Filter table where CreatedBy.Id equals to userId
    .Skip((page - 1) * amount) // Skips some amount of data and returns IQuerable<FavouriteField>
    .Take(amount) // Takes some amount of data and returns IQuerable<FavouriteField>
    .Select(x => x.Field); // Selects Field entity

Upvotes: 3

Related Questions