简体   繁体   中英

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

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?

I think what you actually want is FromSqlRaw https://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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM