【问题标题】:Unable to select just certain columns from table with Entity Framework - get anonymous type error无法使用实体框架从表中仅选择某些列 - 出现匿名类型错误
【发布时间】:2014-07-20 17:23:22
【问题描述】:

我正在尝试使用 EF 6.1 从表中仅选择某些列。但是,它不会让我只撤回我想要的列。我必须从有 14,000 行的表中拉回每一列,因此查询需要大约 30 秒。终止查询的列是表中的 NVARCHAR。但是对于 EF,要么全有,要么全无。我也在使用 IEnumerable。也许我应该使用 IQueryable?>

使用这个查询我得到一个匿名类型错误:

 Using db As Ctx = New Ctx
     Dim postcount = db.be_Posts.Count
     posts = db.be_Posts.Select(Function(S) New With {S.DateCreated, S.Description, S.PostRowID, S.Title}).OrderByDescending(Function(x) x.DateCreated)
     Return posts.ToList
 End Using

错误:

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[VB$AnonymousType_0`4[System.DateTime,System.String,System.Int32,System.String]]' to type 'System.Collections.Generic.IEnumerable`1

这可行,但正在获取我不需要的所有记录和列:

Using db As Ctx = New Ctx
            Dim postcount = db.be_Posts.Count
            posts = db.be_Posts.OrderByDescending(Function(x) x.DateCreated).ToList

            Return posts
        End Using

【问题讨论】:

    标签: sql-server asp.net-mvc vb.net asp.net-mvc-5.1 entity-framework-6.1


    【解决方案1】:

    我会做的是:

    1. 创建 PostSummaryDto 类:

      公共类 PostSummaryDto { 公共日期时间 DateCreated { 获取;放; } ...其他领域... }

    2. 在查询中使用 PostSummaryDto 类:

      New PostSummaryDto { DateCreated = S.DateCreated, ...}

    3. 定义函数的返回类型为IEnumerable<PostSummaryDto>

    我不是 Visual Basic 的粉丝,所以我不确定是否允许返回匿名类型,但我相信明确定义返回类型是一种很好的习惯。

    【讨论】:

    • 谢谢。这有助于加快查询速度。现在我只需要弄清楚如何将 Troy Goode 的 ToPagedList 扩展与存储库一起使用,或者实现我自己的分页解决方案。
    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多