c# - EF 中的常量导致异常

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

最佳答案

一种简单的方法是从数据库中获取所有值到一个匿名类型,然后在最终投影之前使用 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();
 }

关于c# - EF 中的常量导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11265682/

相关文章:

c# - Entity Framework 从表达式生成错误的参数类型

c# - 计算属性(property)总和

c# - 如何删除linq查询中的重复项

.net - 如何清除客户端 .Net SSL session 缓存

c# - 表达式的结果始终为真

c# - EF 忽略 ON DELETE CASCADE 的流畅 API

c# - 提高字符串解析性能

c# - 将日期转换为 dd-mm-yyyy 格式

.net - WPF 为 Silverlight/Windows Phone 7 设计自定义 UI 组件

asp.net - 如何跨多个 ASP.NET 请求更新 EF 中的实体而无需再次检索它?