Search code examples
entity-frameworkentity-framework-coreiqueryabledynamic-linqdynamic-linq-core

Asp.net core - Entity Framework core - add additional data to a view object while keeping it a Queryable


    [EnableQuery]
    public ActionResult<IQueryable<OurView>> GetInteractionRecordings(int pageNumber)
    {
        IQueryable<OurView> ourViews = _dbContext.OurView
            .Skip((pageNumber - 1) * 100)
            .Take(100)
            .AsQueryable();

        // One of the fields in OurView is a PhotoPath (string) that's not in the database.
        // We want to add that PhotoPath to every row without enumerating (function call for each row)
        // As we want to keep it a queryable

        return Ok(ourViews);
    }

Regardless of the solution, most importantly, what we want to avoid is the following:

Let's assume there are 500,000 records in the database table, enumerating all these records in the table before executing "Take" or the PhotoPath lookups.

We want it as a Queryable as we are utilizing Odata.


Solution

  • You can do that via Select:

    var ourViews = _dbContext.OurView
        .Skip((pageNumber - 1) * 100)
        .Take(100);
    
    var photoPath = "SomePath";
    
    var withAdditionalData = ourViews
        .Select(x => new 
        {
            Id = x.Id,
            // other fields
    
            PhotoPath = photoPath
        });