I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string. Here's the Query:
var query = (
from f in Context.Files
orderby f.DateAdded descending
select new
{
Concerns = f.Concerns.Name,
Sender = f.Sender.Name,
CategoryCount = f.Categories.Count(),
DateAdded = f.DateAdded,
Comment = (f.Comment == null || f.Comment.Length < 5)
? f.Comment : f.Comment
}).Take(10);
So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.
However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:
Comment = (f.Comment == null || f.Comment.Length < 5)
? f.Comment : f.Comment
With this line:
Comment = (f.Comment == null || f.Comment.Length < 5)
? f.Comment : f.Comment.SubString(0,5)
the application throws a XamlParseException (???)
The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception
I really don't know why it would do that. Is the SubString method not supported in LINQ?
Hope someone can help me here. Until then, I'll just leave it the way it is.
EDIT 2 (Somehow, my first edit got lost. So I'm redoing it): Based on the comments I got I changed my code to this and it works now:
var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
.Select(File => new
{
Concerns = File.Concerns.Name,
Sender = File.Sender.Name,
CategoryCount = File.Categories.Count(),
DateAdded = File.DateAdded,
Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
});
I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.