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.
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}'") .
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With