0

I am doing a simple query with a .Select() on a database view and was expecting to see a shorter list of columns in the generated SQL:

DbContext.LeadSearch.Select(ls => new
        {
            ls.Id,
            ls.BrokerName,
            ls.UpdateDate
        }).Take(2).ToList();

The generated SQL included all of the columns though:

SELECT TOP(@__p_0) [ls].[Id], [ls].[AssetNumber], [ls].[BrokerId],
[ls].[BrokerName], [ls].[FirstName], [ls].[IsApproved],
[ls].[LastName], [ls].[PurchaseAmount], [ls].[Yadda], [ls].[Yadda2], 
... [ls].[UpdateDate] FROM [dp].[vwLeadSearch] AS [ls]

From what I have read elsewhere I was expecting the SQL to have just the "Selected" columns.

LeadSearch is defined as a DbSet:

public DbSet<LeadSearch> LeadSearch { get; set; }

Mapped to the view:

modelBuilder.Entity<LeadSearch>().ToTable("vwLeadSearch").HasKey("Id");

This is with EF Core 2.1.1.

5
  • If LeadSearch is a DbSet and the entity class is mapped properly, yes. Commented Aug 14, 2018 at 9:53
  • Can you provide more context because what you are describing does not happen with DbSets. When you say database view, how it is mapped in EF Core - DbSet or DbQuery with ToView? Commented Aug 14, 2018 at 12:00
  • @IvanStoev Question has been edited. Notat that the .Select() works as expected on a table. I also tried switching the view to use modelBuilder.Query<LeadSearch>().ToView("vwLeadSearch") but the SQL statement still contained all columns. Commented Aug 14, 2018 at 19:54
  • 1
    Thanks. Unfortunately I can't reproduce using both approaches - I'm getting just the selected columns as expected. Commented Aug 14, 2018 at 20:04
  • 2
    @IvanStoev Thanks for proving that it works as expected. It helped me track down what I was doing wrong, Commented Aug 16, 2018 at 0:55

1 Answer 1

2

One of the "columns" I included in the Select() was actually a calculated property on the class:

public string Name => FirstName + " " + LastName;

EF was smart enough to know it had to get all of the columns in order for this expression to complete. Changing my Select to get FirstName and LastName instead of Name fixed the issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.