Reputation: 1031
I am using Entity Framework in an MVC website
I am trying to get just the number of records using a raw query.
I am looking for something along these lines but any will be happy with any solution at all.
var sql = SELECT COUNT(*) FROM dbo.Articles WHERE (CategoryID = 3)
var total = _context.Database.SOMETHING(sql)
I realise that for such a simple scenario, a raw query is perhaps not the way to go but in reality, the sql string is MUCH more complicated so it is next to impossible for to use Linq to SQL.
Upvotes: 32
Views: 33707
Reputation: 381
An update for the approved answer above with a EF Core 7.
var sql = "SELECT COUNT(*) AS Value FROM dbo.Articles WHERE (CategoryID = 3)";
var total = _context.Database.SqlQueryRaw<int>(sql).First();
with SqlQuery
int categoryId = 3;
var total = _context.Database.SqlQueryRaw<int>($"SELECT COUNT(*) AS Value FROM dbo.Articles WHERE (CategoryID = {categoryId})").First();
Upvotes: 6
Reputation: 139758
You can execute raw SQL queries with EF code first with using the SqlQuery method:
var sql = "SELECT COUNT(*) FROM dbo.Articles WHERE (CategoryID = 3)";
var total = _context.Database.SqlQuery<int>(sql).First();
Upvotes: 70