admin管理员组

文章数量:1400982

I created DTOs with GraphQL to avoid exposing entities outside of my project and also we have REST APIs and entity AppDbContext in our existing project . While the DTOs return the requested data

{
  "data": {
    "stocks": [
      {
        "symbol": "hij"
      },
      {
        "symbol": "abc"
      },

but it selects all the properties in the select list and filters out in memory, resulting in bad SQL queries that select all columns.

I request just symbols:

{
  stocks {
    symbol
  }
}

The query generated is as shown below in efficiently selects 'created'

SELECT [c].[symbol] AS [Symbol], [c].[created] AS [Created]
FROM [company] AS [c]

C# .NET and Entity Framework Core code

[UseFiltering]
[UseSorting]
public IQueryable<StockResponseDTO> GetStocks([Service] ICompanyRepository stockRepository)
{
      return stockRepository.ReadAll().Select(stock => new StockResponseDTO
      {
          Symbol = stock.Symbol,
          Created = stock.Created,
      });
}

public class StockResponseDTO
{
      public string Symbol { get; set; }
      public DateTime? Created { get; set; } // Nullable to handle missing values
}

And also if I request like below, it selects all columns in efficient query

{
  stocks {
    symbol,
    isin
  }
}

Repo

 public IQueryable<EntityFramework.App.Company.Company> ReadAll()
 {
     return _dbContext.Company;
 }
[UseFiltering]
[UseSorting]
public IQueryable<App.EntityFramework.App.Company.Company> GetStocks([Service] ICompanyRepository stockRepository)
{
    return stockRepository.ReadAll();
}

in efficient query executed

SELECT [c].[Id], [c].[created], [c].[isin], [c].[symbol]
FROM [company] AS [c]

本文标签: