0

Here is my SQL query. I'm trying to produce the same results in my .NET Core web app using a linq query.

SELECT * 
FROM dbo.BUD
WHERE LEFT(PeriodD, 4) = YEAR(GETDATE())

Here is what I've tried with no success in my linq query

List<SelectListItem> budNames = _ctx.Budgets.AsNoTracking()     
            .Where(n => (n.Period, 4) == GETDATE())  
            .Select(n => new SelectListItem
                             {
                                 // values
                             }).ToList();
3
  • Is n.Period of type DateTime? Commented Jun 25, 2021 at 13:05
  • Its a character fields YYYYMM, sorry that probably would have been helpful. Commented Jun 25, 2021 at 13:06
  • The comparison must be all means include YEAR(GETDATE()) - otherwise, you're comparing to one specific moment in time - not a whole yeaR! Commented Jun 25, 2021 at 14:12

1 Answer 1

2

Mainly this line causes you problems:

.Where(n=> (n.Period,4) == GetDate())  

To get the first 4 characters of a string, use the Substring method:

n.Period.Substring(0, 4) // beginn 0 away from the first char, take 4 of them

To get a sting of the current year (DateTime):

var currentYear = DateTime.Now.ToString("yyyy");

Applied to your example:

var currentYear = DateTime.Now.ToString("yyyy");
List<SelectListItem> budNames = _ctx.Budgets.AsNoTracking()     
    .Where(n => n.Period.Substring(0, 4) == currentYear)  
    .Select(n => new SelectListItem
    {
        // values
    }).ToList();

Or, you could use the StartsWith method:

var currentYear = DateTime.Now.ToString("yyyy");
List<SelectListItem> budNames = _ctx.Budgets.AsNoTracking()     
    .Where(n => n.Period.StartsWith(currentYear))  
    .Select(n => new SelectListItem
    {
        // values
    }).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.