简体   繁体   中英

How to write entity framework query and Linq query on c#?

在此处输入图片说明

Hi, I have this table. I want to write this query in my controller.

select sum(Amount) from tbl_Amounts where fk_Roleid=2

which shows result of 800 in sql. I don't know how to write it in both EF and Linq. If someone could kindly show me the way to write in both ways would be really helpfull.

This should basically be the Linq syntax for your request.

Linq is some "internal framework" of .NET / C#, and you use Entity framework.

There is no real meaning in separating the two, in my opinion.

This is the "Linq to SQL" syntax I would use on the "DataContext" that you cretate with EF :

DataContext
    .tbl_Amounts
    .Where(a => a.fk_Roleid = 2)
    .Sum(a => a.Amount);

If you have a collection of record called Amounts, this would be the "linq to objects" version :

Amounts
    .Where(a => a.fk_Roleid = 2)
    .Sum(a => a.Amount);

As you can see, there is no real difference ! (excepted that, under the hood, the first one on an EF Data Context will be converted to a SQL db request)

But it could actually depends on your Entity Framework version (not all linq features are correctly translated to SQL)

There are 3 different ways to execute SQL query in Entity Framework (EF), depending on the version you're using:

1) Using LINQ to Entities (all versions)

using (var db = new DataContext())
{
    int amount = (from am in db.tbl_Amounts where am.fk_Roleid == 2 select am.amount).Sum();
}

2) Using Database.SqlQuery<T>() (up to EF 6)

using (var db = new DataContext())
{
    string query = "select sum(Amount) from tbl_Amounts where fk_Roleid=2";
    int amount = db.Database.SqlQuery<int>(query).Single(); // or First()
}

3) Using FromSql() (EF Core)

using (var db = new DataContext())
{
    string query = "select sum(Amount) from tbl_Amounts where fk_Roleid=2";
    int amount = db.tbl_Amounts.FromSql(query).Single(); // or First()
}

Note that if you're using EF Core, Database.SqlQuery<T> doesn't exist and you should use Execute raw SQL query in EF Core .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM