I'm writing a LINQ query to fill a listview
but it uses the .ToString()
method which apparently is not allowed. When I use the below code I get the error message:
Error: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression
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 know 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();
}
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();
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.