Search code examples
asp.net-mvclinqasp.net-mvc-5entity-framework-6asp.net-mvc-5.1

Is there a way to get the data by day name in entityframework


I am trying to write code to get news on there publishing date and day,,,,,like

             ViewBag.LatestNews = db.News
            .Where(ve => ve.PublishingDate >= DateTime.Now 
            && ve.IsActive == true);

The output i get is correct according to requirement.... I need to filter publishing date on the DayOfWeek lets say "Sunday"... How to write parameter that takes the day number and filter the result. Any one help please.... Thanks for you time


Solution

  • Try this:-

    ViewBag.LatestNews = db.News
                           .Where(ve => (int)ve.PublishingDate.DayOfWeek == 7 
                                           && ve.IsActive == true);
    

    Or:-

    ViewBag.LatestNews = db.News
                           .Where(ve => ve.PublishingDate.DayOfWeek.ToString() == "Sunday" 
                                           && ve.IsActive == true);
    

    Edit:
    You can use SqlFunctions.DatePart method for linq to entity:-

    ViewBag.LatestNews = db.News
                 .Where(ve => SqlFunctions.DatePart("dw", ve.PublishingDate) == "Sunday" 
                              && ve.IsActive == true);