Search code examples
c#sqlentity-frameworklambda

EF Lambda for SQL : How to get a new column based on some string presence in other column of the same table


I want SQL query equivalent in EF Core Lambda, to get an extra column as either true or false, based on some substring(in this case DEALER) if present in other column's data of the same table.

myTable
     Id                        col1
     1              I have substring - DEALER
     2              I do not have any substring 

I need the output as

Id,                IsDealer
1,                  true   
2,                  false   

I tried the following SQL query,

SELECT [Id] , 
CASE WHEN [col1] LIKE '%DEALER%' THEN 'true' ELSE 'false' END as IsDealer 
FROM [dbo].[myTable]

I get proper output, But what is the above SQL query EF CORE equivalent ?

I tried

_Context.myTable.Where(et => et)
                        .Select(s => new myTableEFCoreModel
                         {
                             Id = s.Id,
                            **<what goes here for IsDealer>**
                        });

Solution

  • You're returning the string in col1 so just doing a string compare should be all you need:

    _Context.myTable.Where(et => et)
        .Select(s => new myTableEFCoreModel
        {
            /* same as select [Id] in sql query */
            Id = s.Id, 
            /* same as case when [col1] like "%DEALER%" then 'true' else 'false' as IsDealer */
            IsDealer = s.col1.Contains("DEALER") 
         });