Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I achieve SQL CASE statement from LINQ

I am new to LINQ and I would like to know if I can achieve the below SQL query from LINQ?

I am using Entity Framework Core.

SELECT 0 [All], [Range] =
    CASE  
        WHEN Value BETWEEN 0 AND 25 THEN 'Low' 
        WHEN Value BETWEEN 25 AND 75 THEN 'Medium' 
        WHEN Value BETWEEN 75 AND 90 THEN 'High' 
        WHEN Value BETWEEN 90 AND 100 THEN 'Very High' 
    END 
FROM Result.Calculation C 
    INNER JOIN Data.SampleSet S ON C.SampleSetID = S.ID  
WHERE  S.SampleDrawn >= DATEADD(MONTH,-3,GETDATE()) AND S.Department = 'LOCATION A'

Currently, I am using FromSql as below to call a stored procedure. I would like to know whether I can do the same without using stored procedures?

var result = context.MyData.FromSql("data.GetMyData @pType = {0}, @pLocation = {1}, @pNoOfDays = {2}, @pStartDate = {3}, @pEndDate = {4}", type, location, noOfDays, startDate, endDate).ToList();

Thanks.

like image 962
Geshem W Avatar asked Jan 03 '23 09:01

Geshem W


1 Answers

You can use this.

from C in Calculations
join S in SampleSets on C.SampleSetID equals S.ID 
where S.SampleDrawn >= DateTime.Now.AddMonths(-3)
      && S.Department == "LOCATION A"
select new {
    All = 1 
    , Range = 
        (C.Value >= 0 && C.Value < 25) ? "Low" :
        (C.Value >= 25 && C.Value < 75) ? "Medium" :
        (C.Value >= 75 && C.Value < 90) ? "High" :
        (C.Value >= 90 && C.Value <= 100) ? "Very High" : null
}
like image 94
Serkan Arslan Avatar answered Jan 12 '23 07:01

Serkan Arslan