使用原始查询返回计数,使用Entity Framework和MVC

时间:2022-01-10 09:50:45

I am using Entity Framework in an MVC website

我在MVC网站上使用Entity Framework

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.

我意识到,对于这样一个简单的场景,原始查询可能不是可行的方法,但实际上,sql字符串要复杂得多,因此几乎不可能使用Linq to SQL。

1 个解决方案

#1


41  

You can execute raw SQL queries with EF code first with using the SqlQuery method:

您可以使用SqlQuery方法首先使用EF代码执行原始SQL查询:

var sql = "SELECT COUNT(*) FROM dbo.Articles WHERE (CategoryID = 3)";
var total = _context.Database.SqlQuery<int>(sql).First();

#1


41  

You can execute raw SQL queries with EF code first with using the SqlQuery method:

您可以使用SqlQuery方法首先使用EF代码执行原始SQL查询:

var sql = "SELECT COUNT(*) FROM dbo.Articles WHERE (CategoryID = 3)";
var total = _context.Database.SqlQuery<int>(sql).First();