我有以下代码。但它会导致例外。
using (var context = new blogEntities())
{
var listOfComments = context.Comments
.OrderByDescending(c => c.CreateDate)
.Where(c => c.CreateDate > fromDate)
.Select(c => new NewsFeedData()
{
ArticleID = c.ArticleID,
CommentID = c.CommentID,
Text = c.CommentText,
Author = c.Author,
CreateDate = c.CreateDate,
Type = 'C'
}).ToList();
}
比我尝试枚举,但有一些问题。实现我想要的最好方法是什么? 我想为Type
分配一些常量答案 0 :(得分:4)
一种简单的方法是将数据库中的所有值提取为匿名类型,然后在最终投影之前使用AsEnumerable
切换到LINQ to Objects:
using (var context = new blogEntities())
{
var listOfComments = context.Comments
.OrderByDescending(c => c.CreateDate)
.Where(c => c.CreateDate > fromDate)
.Select(c => new { c.ArticleID, c.CommentID, c.CommentText,
c.Author, c.CreateDate })
.AsEnumerable() // Switch into LINQ to Objects
.Select(c => new NewsFeedData
{
ArticleID = c.ArticleID,
CommentID = c.CommentID,
Text = c.CommentText,
Author = c.Author,
CreateDate = c.CreateDate,
Type = 'C'
}).ToList();
}