33

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.

2
  • 1
    What is the type of _context? DbContext, DataContext, ObjectContext ? Commented Apr 14, 2012 at 14:57
  • @nemesv. It is a DbContext ( sorry, it did not realise that Entity Framework could have different things - I am obviously new to this game). Does knowing it is DbContext mean you can help me? Commented Apr 14, 2012 at 15:03

2 Answers 2

70

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! That worked perfectly after I changed the last line to var total = _context.Database.SqlQuery<int>(sql).single();
But i have to use dynamic as below, var sql = "SELECT * FROM dbo.Articles"; dynamic total = _context.Database.SqlQuery<dynamic>(sql).ToList(); ..... Is this possible??
8

An update for the approved answer above with a EF Core 7.

  1. name the column 'AS Value'. It must be named like this, it fails otherwise.
  2. use SqlQueryRaw because SqlQuery requires a FormattableString and 'sql' is not such. However, it can be re-written with SqlQuery.
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();

1 Comment

Adding 'AS Value' works well in EF Core 7, thanks! You can use SqlQuery (not only SqlQueryRaw) if using interpolated strings for parameterization.

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.