How do I make a raw sql query in EF Core 2.2?

c# entity-framework-core

Question

I'm working with a dotnet core 2.x application.

We've got a bunch of "code first" entities, and a DBSet for each in the DBContext.

EXAMPLE:

public class MyContext : DBContext
{
  public MyContext(DBContextOptions<MyContext> options) : base (options) {}

  public DbSet<Models.MyTable> MyTable { get; set; }
  ...

So far, so good. Now I'd like to make this query:

SELECT DISTINCT MyColumn from dbo.MyTable

Should be easy, right? "Classic EF" had dbData.Database.SqlQuery<SomeModel>, but in EF Core 2.x I should be able to do something like this:

var myList = _context.MyTable.FromSql("SELECT DISTINCT MyColumn from dbo.MyTable").ToList();

This fails:

ERROR CS1061: DbSet does not contain a definition for FromSql...

I read that maybe I needed to install an additional package, "Microsoft.EntityFrameworkCore.Relational". But NuGet > Browse only showed me v3.1 (no 2.x versions) ... and installing this package wanted to bring in many, many other dependencies (!)

QUESTION:

Is there any way to make a simple SQL query with EF Core 2.x ...

... that DOESN'T require "select *" (bringing in the whole table!) and DOESN'T require downloading and installing a bunch of additional NuGet dependencies?

1
3
3/9/2020 5:28:56 AM

Accepted Answer

Thank you, Ivan Stoev. The solution was to use a LINQ "Select":

var myList = _context.MyTable.Select(e => e.MyColumn).Distinct().ToList();

This worked like a charm ... and it does NOT require any external dependencies.

1
3/9/2020 4:45:50 PM

Popular Answer

I think what you actually want is FromSqlRawhttps://docs.microsoft.com/en-us/ef/core/querying/raw-sql

in any case, If you're in EF, you shouldn't need to do that for such a simple query. EF select does NOT require you to get the data from the entire table schema. You can specify with a .select the exact columns you want.

see https://www.brentozar.com/archive/2016/09/select-specific-columns-entity-framework-query/ for more information.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow