在LINQ查询中使用ToString()? [英] Using ToString() in LINQ queries?
问题描述
我已经写了一个LINQ查询来填充列表视图,但是它使用了.ToString()方法,这显然是不允许的.当我使用下面的代码时,我收到错误消息:
I have writting a LINQ query to fill a listview but it useses the .ToString() method which apparetly is not allowed. When I use the below code I get the error message:
错误:LINQ to Entities无法识别方法'System.String ToString()',并且该方法无法转换为商店表达式
Error: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
有没有一种方法可以在LINQ中使用ToString(),或者如果不可能,在查询中将DateTime转换为String的解决方案是什么?请注意,ReleaseDateName是字符串,ReleaseDate是DateTime
Is there a way to use the ToString() in LINQ or if that is not possible what is the solution to converting a DateTime to String in the query. Please knot that ReleaseDateName is a string and ReleaseDate is a DateTime
using (var db = new ReleaseInfo())
{
lvReleaseInfo.DataSource = (from r in db.MediaReleases
join rn in db.ReleaseNames
on new { MediaReleaseID = r.MediaReleaseID, CultureCodeID } equals new { rn.MediaReleaseID, rn.CultureCodeID }
join plat in db.MediaPlatforms
on new { MediaPlatformID = r.MediaPlatformID, CultureCodeID } equals new { plat.MediaPlatformID, plat.CultureCodeID }
join pub in db.MediaPublishers
on new { MediaPublisherID = r.MediaPublisherID, CultureCodeID } equals new { pub.MediaPublisherID, pub.CultureCodeID }
join c in db.Countries
on new { CountryID = r.CountryID, CultureCodeID } equals new { c.CountryID, c.CultureCodeID }
join rd in db.ReleaseDates
on new { MediaReleaseID = r.MediaReleaseID, CultureCodeID } equals new { rd.MediaReleaseID, rd.CultureCodeID }
join a in db.AffiliateLinks
on new { MediaReleaseID = r.MediaReleaseID, CultureCodeID } equals new { a.MediaReleaseID, a.CultureCodeID }
where r.SectionID == SectionID
select new
{
rn.ReleaseTitle,
plat.MediaPlatformName,
pub.MediaPublisherName,
c.CountryName,
ReleaseDate = (rd.ReleaseDate == null ? rd.ReleaseDateName : rd.ReleaseDate.ToString()),
a.AffiliateLinkAddress
}).ToList();
lvReleaseInfo.DataBind();
}
推荐答案
由于您正在具体化要列出的查询,因此可以在.NET端而不是在RDBMS中进行转换,如下所示:
Since you are materializing your query to list anyway, you could do the conversion on the .NET side, rather than in the RDBMS, like this:
...
select new {
rn.ReleaseTitle,
plat.MediaPlatformName,
pub.MediaPublisherName,
c.CountryName,
rd.ReleaseDateName,
rd.ReleaseDate,
a.AffiliateLinkAddress
}).AsEnumerable() // <<== This forces the following Select to operate in memory
.Select(t => new {
t.ReleaseTitle,
t.MediaPlatformName,
t.MediaPublisherName,
t.CountryName,
ReleaseDate = t.ReleaseDateName ?? t.ReleaseDate.ToString()
t.AffiliateLinkAddress
}).ToList();
由于在IEnumerable<T>
中的元素上调用了ToString()
,因此它将不再失败.还要注意,使用??
运算符代替了对空检查? :
的条件.
Since the ToString()
is called on an element from IEnumerable<T>
, it will no longer fail. Also note the use of ??
operator in place of a null-checking ? :
conditional.
这篇关于在LINQ查询中使用ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!