Reputation: 121599
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?
Upvotes: 2
Views: 1756
Reputation: 121599
Per the comment from Ivan Stoev, the solution was to use a LINQ "Select":
var myList = _context.MyTable.Select(e => e.MyColumn).Distinct().ToList();
This worked well, and it does not require any external dependencies.
Upvotes: -1
Reputation: 2175
I think what you actually want is FromSqlRaw
https://learn.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.
Upvotes: 1