Using ToString() in LINQ queries?

大兔子大兔子 提交于 2019-12-05 11:15:56

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.

The problem is that you can't call ToString() on a field until it's been deserialized. So, rather than trying to call ToString() in the query, simply do it on the results afterwards.

In the database the value you're operating on has no notion of ToString() which is why you get the error. The query may look and feel like C# code but keep in mind that under the covers that is being transformed to a SQL query like any other. After you get the list back you can write a very simple LINQ query to solve the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!