【问题标题】:Constant in EF causes exceptionEF 中的常量导致异常
【发布时间】:2012-06-29 16:37:43
【问题描述】:

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

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

【问题讨论】:

  • 有什么异常? “类型”是一个字符吗?
  • 无法创建“System.Char”类型的常量值。此上下文仅支持原始类型(“例如 Int32、String 和 Guid”)。 NotSupportedException

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


【解决方案1】:

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

【讨论】:

  • @levanlevi:这个解决方案非常完美!非常酷的技巧......我怀疑有没有更少代码的方法。
  • @levanlevi:“太大”是什么意思?我只加了三行代码……如果能解决你的问题,那三行是不是要求太多了?
  • 好的,代码更少 :) 在AsEnumerable 之前和之后使用new NewsFeedData.Select(c => { c.Type = 'C'; return c; }).ToList()
  • @Slauma: Ick - 虽然这应该可行,但我肯定会使用我的版本;)
猜你喜欢
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 2017-03-23
相关资源
最近更新 更多