我遇到了一种情况,我需要让 LINQ to Entities 查询根据字符串的长度返回一个子字符串。
这是查询:
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);
所以我正在做的是获取最后 10 个添加的文件类型实体,然后从中选择一组属性以显示在列表视图中。有些是纯字符串(关注点、发件人)。 CategoryCount 返回与 File 对象关联的类别数。
但是,如果注释长于给定长度,我希望将其截断。在上面的代码中,一切都工作正常。现在当我替换这一行时:
Comment = (f.Comment == null || f.Comment.Length < 5)
? f.Comment : f.Comment
有了这一行:
Comment = (f.Comment == null || f.Comment.Length < 5)
? f.Comment : f.Comment.SubString(0,5)
应用程序抛出 XamlParseException (???)
对与指定绑定约束匹配的“DocumentManager.Views.ListEntriesView”类型的构造函数的调用引发了异常
我实在不知道为什么它会这么做。 LINQ 不支持 SubString 方法吗?
希望有人可以在这里帮助我。在那之前,我将保持原样。
编辑2(不知何故,我的第一次编辑丢失了。所以我正在重做它):
根据我收到的评论,我将代码更改为这样,现在它可以工作了:
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) + "..."
});
我忘了提及我正在使用 SQLite。所以也许 Substring 没有在 SQLite EF Provider 中实现。