Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return count using raw query, using Entity Framework and MVC

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.

like image 273
Pete Davies Avatar asked Apr 14 '12 14:04

Pete Davies


People also ask

How use raw SQL query in Entity Framework Core?

The FromSql method allows parameterized queries using string interpolation syntax in C#, as shown below. string name = "Bill"; var context = new SchoolContext(); var students = context. Students . FromSql($"Select * from Students where Name = '{name}'") .

How do I run a raw SQL query using DbContext?

From the DbContext 's database object, create the Db command. Then, assign all the required parameters to the command object like the SQL, Command Type, SQL parameters, use existing DB transition, and optional command timeout to the command. Finally, calling ExecuteNonQuery() to execute the raw SQL query.

Which method is used to retrieve data using SQL query statements in EF?

SqlQuery() Use the DbSet. SqlQuery() method to write raw SQL queries which return entity instances. The resulted entities will be tracked by the context, as if they were returned by the LINQ query.


1 Answers

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(); 
like image 172
nemesv Avatar answered Sep 22 '22 23:09

nemesv