Search code examples
c#sqllambda

Lambda Expression Sql to C# DateTime


I have the following query in sql database:

SELECT a.GroupCode, a.GroupDate 
FROM TableP 
WHERE YEAR(a.GroupDate) = '2023' 
AND a.GroupCode LIKE '0100%';

How can I change it into Lambda Expression? What I did is like below:

List<TableP> list = await _context.TablePs
            .Where(x => x.GroupCode.StartsWith(request.GroupCode) && x.GroupDate == request.GroupDate)
            .ToListAsync(cancellationToken);

So from the lambda above, I want to change x.GroupDate like YEAR(a.GroupDate). Then I will create a parameter as a string.

Advice please.
Thank you.


Solution

  • if DataType GroupDate is DateTime ,You can use g.GroupDate.Year and linq translate to DATEPART(year, [p].[GroupDate])

    Example

    var _result = context.TablePs
    .Where(d => x.GroupCode.StartsWith(request.GroupCode) 
               && d.GroupDate.Year == request.GroupDate.Year).ToList();
    

    i qet my query with profiler

    SELECT *
    FROM [Persons] AS [p]
    WHERE ([p].[GroupCode] LIKE N'dd%') AND DATEPART(year, [p].[GroupCode]) = 2023