【问题标题】:Use IQueryable on stored procedure in Entity Framework在实体框架中的存储过程上使用 IQueryable
【发布时间】:2016-03-31 04:40:02
【问题描述】:

我正在尝试在存储过程上使用IQueryable,编写存储过程的原因是检查查询中的多个条件。如果我走错了方向,请纠正我。

我假设应用 IQueryable 会比 IEnumerable 快得多,不要忘记我可以在其他实体上使用 IQueryable 没有任何问题。

控制器:

public ActionResult CrmBlogGroupType(int? page, bool? Name, bool? AuthorTitle, bool? Description, string search, int? PageSize, string type)
{
    try
    {
        if (type==null)
        {
            type = "A";
        }

        IQueryable<Usp_getBlogSetPosts_Result> _objBlogSet = _dataLayer.GetBlogSet(type);
        var Result = _objBlogSet.ToPagedList(page ?? 1, PageSize ?? 10);

        return View(_objBlogSet);
}

数据层:

public IQueryable<Usp_getBlogSetPosts_Result> GetBlogSet(string type)
{
        IQueryable<Usp_getBlogSetPosts_Result> Obj = _dbContext.Usp_getBlogSetPosts(type).AsQueryable();
         return Obj;
}

Context.cs:

 public virtual ObjectResult<Usp_getBlogSetPosts_Result> Usp_getBlogSetPosts(string blogSetType)
 {
        var blogSetTypeParameter = blogSetType != null ?
            new ObjectParameter("BlogSetType", blogSetType) :
            new ObjectParameter("BlogSetType", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Usp_getBlogSetPosts_Result>("Usp_getBlogSetPosts", blogSetTypeParameter);
}

错误:

一个查询的结果不能多​​次枚举

【问题讨论】:

  • 现在去掉不相关的东西。就像整个 MVC 的东西。这里没有任何东西是 MVC - 这一切都是一个纯粹的 LINQ 和 EF 查询。
  • 您的想法是错误的 - IQueryable 只有在您构建包含多个 WHERE 组件的查询时才有好处。好处是它尚未执行,您可以添加额外的WHEREORDER BY 表达式,然后在稍后的某个时间点,执行构建的查询并且只有那些匹配所有的行您的标准被返回。对于存储过程,这样做没有任何意义——存储过程已经返回一个最终的、具体化的结果集——这里没有延迟执行模型。
  • 嗨@mar​​c_s,谢谢你让我走上正确的道路,我想要达到的只是速度,因为存储过程将返回一万条记录,我必须再次执行搜索它。有没有什么办法可以提高效率。正如你所看到的,我正在使用一个 Pagedlist 来进行分页..

标签: c# linq entity-framework-4


【解决方案1】:

这是因为存储过程输出结果集的类型不是 IQueryable.. 如果存储过程工作,您必须使用 IEnumerable

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2014-01-25
    • 2011-07-24
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多