LINQ 中的 Smalldatetime ToString

Smalldatetime ToString in LINQ

我有一个 smalldatetime 字段,我正试图将其转换为 LINQ 中的字符串。 这是我当前的代码:

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

但是我收到以下错误:

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

我已经阅读了几篇文章,但我似乎无法让它发挥作用。 任何指针都会很棒。

错误不言而喻,您不能使用无法通过 Linq to Entities 转换为 SQL 的用户定义方法。可以看全文here.

假设你的pubDate是一个字符串,请试试下面的代码

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;

您在比较日期时可能还会遇到时间问题,因此您可以查看 DbFunctions.TruncateTime