J. Raoul FEZE
J. Raoul FEZE

Reputation: 47

LINQ to Entities does not recognize the method 'System.DateTime GetDate()' method, and this method cannot be translated into a store expression

I just started leaning asp.net a couple of months ago and I have some few issues. I receive this error LINQ to Entities does not recognize the method System.DateTime GetDate() method, on the browser while this code works perfectly in Linq. According to what I read in several forum, this error occurs when Linq to Entities cannot translate the code into an SQL query. But I still can't figure out what is wrong with my method.
Here is the class that has the GetDate() method

public class Cycle
{
    private DateTime _Date;

    public DateTime Date 
    { 
        get => _Date;

        set => _Date = value;
    }

    public DateTime GetDate ()
    {
        return this._Date;
    }
}

Here is query that call the method

var RouteList = from site in Sites
                orderby site.Community.Name ascending
                where site.Season.SeasonYear == 2019 && site.Yard.YardID == 1 && site.SiteType.SiteTypeDescription.Equals("A")
                select new Status
                {
                    Pin = site.Pin,
                    Community = site.Community.Name,

                    Cycle1 = ((from sbm in SBMs where sbm.CrewSite.SiteID == site.SiteID select new Cycle { Date = sbm.CrewSite.Crew.TodayDate }).OrderBy(x => x.Date).FirstOrDefault()).Equals(null)
                         ? (DateTime?)null : ((from sbm in SBMs where sbm.CrewSite.SiteID == site.SiteID select new Cycle { Date = sbm.CrewSite.Crew.TodayDate }).OrderBy(x => x.Date).FirstOrDefault()).GetDate()

Can someone help me find out how I can adjust my method ?

Upvotes: 1

Views: 283

Answers (1)

Selim Yildiz
Selim Yildiz

Reputation: 5380

You need to use DbFunctions.TruncateTime() for getting Date of DateTime and use Date property of Cycle instead of custom GetDate method:

var RouteList = from site in Sites
                    orderby site.Community.Name ascending
                    where site.Season.SeasonYear == 2019 && site.Yard.YardID == 1 && site.SiteType.SiteTypeDescription.Equals("A")
                    select new Status
                    {
                        Pin = site.Pin,
                        Community = site.Community.Name,

                         Cycle1 = ((from sbm in SBMs where sbm.CrewSite.SiteID == site.SiteID select new Cycle { Date = DbFunctions.TruncateTime(sbm.CrewSite.Crew) }).OrderBy(x => x.Date).FirstOrDefault()).Equals(null)
                             ? (DateTime?)null : ((from sbm in SBMs where sbm.CrewSite.SiteID == site.SiteID select new Cycle { Date = DbFunctions.TruncateTime(sbm.CrewSite.Crew)}).OrderBy(x => x.Date).FirstOrDefault()).Date

...

Upvotes: 2

Related Questions