EF中的常量会导致异常

时间:2012-06-29 16:37:44

标签: c# .net entity-framework exception enums

我有以下代码。但它会导致例外。

                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

分配一些常量

1 个答案:

答案 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();
 }