Query selects all columns even though only one column is selected

115 Views Asked by At

I have encountered an issue while working with Entity Framework Core 7 where the generated SQL query appears to select all columns from the table, even though I am selecting only one column in my LINQ query.

Here's a simplified version of my code:

var data = dbContext.CandidateData
                    .AsNoTracking()
                    .Where(x => x.CollegeCode == collegeCode
                                && x.Status == CandidateStatus.Active 
                                && ((x.Year == startYear && 
                                     (x.Month >= startMonth && x.Month <= endMonth)) 
                                    || (isDifferentYear ? (x.Year == endYear && x.Month <= endMonth) : false)));

if (someCondition)
{
    beginningScore = await data
                             .Where(x => x.Year == fromDate.Year 
                                         && x.Month == fromDate.Month)
                             .Select(x => x.BeginningScore)
                             .FirstOrDefaultAsync();
}

CandidateData class :

public class CandidateData
{
public int CandidateId {get;set;}
public CollegeCode CollegeCode {get;set;} // this is enum value
public int Year { get; set; }
public int Month { get; set; }
public decimal BeginningScore { get; set; }
}

Fluent Configuration :

public class CandidateDataConfiguration : IEntityTypeConfiguration<CandidateData>
  {
      public void Configure(EntityTypeBuilder<CandidateData> builder)
      {
          builder.HasKey(e => e.CandidateId);
          builder.Property(e => e.CandidateId).ValueGeneratedOnAdd();
          builder.HasIndex(e => new { e.CollegeCode,e.Year, e.Month }).IsUnique().HasDatabaseName("CandidateDataIndex");
      }
  }

In this code, I'm querying the database to fetch data based on certain conditions. However, even though I'm selecting only the BeginningScore column, the generated SQL query seems to select all columns from the table.

I have verified that my LINQ query explicitly selects only the BeginningScore column, and there are no navigation properties involved. Despite this, the SQL generated by EF Core pulls all columns from the table.

Can someone help me understand why EF Core 7 might be behaving this way and how I can optimize my query to only select the specified column?

I've tried using SingleOrDefaultAsync(), using anonymous object projection, but nothing worked as of now, it always pulls all the columns in final generated SQL and also to note specifically here CandidateData table doesn't have single navigational property & data is IQueryable type.

0

There are 0 best solutions below