Search code examples
c#linqentity-framework-coreasp.net-core-webapi

ASP.NET Core Web API using Entity Framework Core


How can I post a request to a table generated from joining two tables in Web API, and return only required columns?

This is the code for that:

    public IActionResult GetAll()
    {
        try
        {
            var clients = _db.Clients
                             .Include(cl => cl.Projects)
                             .ToList();

            return Ok(clients);
        }
        catch(Exception ex) 
        {
            throw;
        }
    }

Solution

  • Maybe you want something like that:

    public IActionResult GetAll()
    {
        try
        {
            var clients = _db.Clients
                          .Include(cl => cl.Projects)
                          .Select(x => new {
                               ColumnName = x.PropertyName,
                               ColumnName2 = x.PropertyName2
                           })
                          .ToList();
            return Ok(clients);
        }
        catch(Exception ex) 
        {
            throw;
        }
    }
    

    This way you create an anonymous object which you can use as you wish