1

我有以下代码。但它会导致异常。

                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 分配一些常量

4

1 回答 1

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();
 }
于 2012-06-29T16:41:20.557 回答