TFFX
TFFX

Reputation: 190

Smalldatetime ToString in LINQ

I have a smalldatetime field that I am trying to convert to a string in LINQ. This is my current code:

var entities = from a in dbcontext.Article
where a.PubDateTime.ToString("ddMMyyyy") == pubDate
select a;

However I get the following error:

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

I have read a few posts however I can't seem to get it to work. Any pointers would be great.

Upvotes: 2

Views: 761

Answers (1)

Atlasmaybe
Atlasmaybe

Reputation: 1549

The error speaks for itself, you can't use a User defined method that can't be translated to SQL through Linq to Entities. You can see a full article here.

Assuming that your pubDateis a string, please try that following code

DateTime date = DateTime.Parse(pubDate); // You may have to specify your own format
DateTime date2 = DateTime.ParseExact(pubDate,"ddMMyyyy",System.Globalization.CultureInfo.Invarian‌​tCulture); // Like suggested by XenoPuTtSs

// choose date or date2, according to your needs

var entities = from a in dbcontext.Article
    where a.PubDateTime == date
    select a;

You may also have trouble with time when comparing dates like that, so you could check DbFunctions.TruncateTime.

Upvotes: 1

Related Questions