Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of "CASE WHEN THEN" (T-SQL) with Entity Framework?

I have a Transact-SQl request that I use a lot and I want to get the equivalent with Entity Framework. But I don't know how to make a "CASE WHEN" statement with EF. Here is a simplified code of my request :

SELECT Code,
SUM(CASE WHEN Month=1 THEN Days Else 0 END) AS Jan,
FROM MyTable 
GROUP BY Code

Can you tell me if it's possible and how to do this with EF ?

like image 323
Alex Avatar asked Dec 10 '13 14:12

Alex


People also ask

Can you execute T SQL statements using Entity Framework?

Execute Raw SQL Queries in Entity Framework 6. Entity Framework allows you to execute raw SQL queries for the underlying relational database.

Can we use case and if statement in SQL?

SQL Server CASE statement is equivalent to the IF-THEN statement in Excel. The CASE statement is used to implement the logic where you want to set the value of one column depending upon the values in other columns. The SQL Server CASE Statement consists of at least one pair of WHEN and THEN statements.

Which is better Entity Framework or LINQ to SQL?

LINQ to SQL allow you to query and modify SQL Server database by using LINQ syntax. Entity framework is a great ORM shipped by Microsoft which allow you to query and modify RDBMS like SQL Server, Oracle, DB2 and MySQL etc. by using LINQ syntax. Today, EF is widely used by each and every .

What is the alternative to Entity Framework?

NHibernate, Entity Framework Core, Hibernate, Sequelize, and SQLAlchemy are the most popular alternatives and competitors to Entity Framework.


2 Answers

In this case, I'd say the conditional operator (p ? x : y) is a good substitute.

// context.MyTable is an IQueryable<MyTable>
var query = from t in context.MyTable
            group t by t.Code into grp
            select
            new {
                Code = grp.Key,
                Jan = grp.Sum(x => x.Month == 1 ? x.Days : 0),
            };

Or combine a Where and a Sum:

                Jan = grp.Where(x => x.Month == 1).Sum(x => x.Days),

I'm not sure what SQL these translate to exactly, but they should both have the same result.

like image 99
Tim S. Avatar answered Nov 02 '22 22:11

Tim S.


as illustrated by the following, the linq equivalent of transact sql CASE WHEN THEN is the conditional operator ?: :

from u in Users
select new {
name = u.Login,
imported = (u.ImportedId != null ) ? 1 : 0
}

is translated as

SELECT 
1 AS [C1], 
[Extent1].[Login] AS [Login], 
CASE WHEN ([Extent1].[ImportedId] IS NOT NULL) THEN 1 ELSE 0 END AS [C2]
FROM [dbo].[VIPUsers] AS [Extent1]
like image 44
tschmit007 Avatar answered Nov 02 '22 21:11

tschmit007