将类对象的IQueryable从视图发送到控制器类

时间:2015-01-16 15:24:42

标签: c# asp.net-mvc linq

我在MVC应用程序

中从视图返回IQuerable对象时遇到错误

enter image description here

public partial class Course_Services
{
    #region Process All Courses Application's URL
    public IQueryable<CourseInstanceModel> ProcessAllCoursesApplicationURL(CourseApplicationsURLFeed_Model _obj)
    {
        IQueryable<CourseInstanceModel> ListOfCoursesInstances; 

        //get all the courses which have Application URL is Null..
        using(var _uof = new Courses_UnitOfWork())
        {
            ListOfCoursesInstances = _uof.CourseInstances_Repository.GetAll();

          var _listOfCoursesWithoutURL = from b in ListOfCoursesInstances 
                                           where b.ApplicationURL == null
                                           select ListOfCoursesInstances;

          return _listOfCoursesWithoutURL;
        }
    }
    #endregion
}

我很难理解我在做错的地方。非常感谢提前

3 个答案:

答案 0 :(得分:1)

select ListOfCoursesInstances

您刚刚为select子句中的每个元素返回了整个源集合。

正如错误试图告诉你的那样,这会产生一系列集合,这不是你想要的。

您可能想要选择原始项目(b

答案 1 :(得分:1)

你选择了错误的东西。您应该选择您在那里创建的b变量。

var _listOfCoursesWithoutURL = from b in ListOfCoursesInstances 
                               where b.ApplicationURL == null
                               select b;

现在你拥有它的方式是为该列表中的每个元素选择ListOfCoursesInstances一次。由于ListOfCourseInstances本身就是IQueryable<CourseInstanceModel>,这意味着您要返回IQueryable<IQueryable<CourseInstanceModel>>,这对您所拥有的方法无效,只返回IQueryable<CourseInstanceModel>

或者,你也可以做@Steve在评论中写的内容,即:

return ListOfCoursesInstances.Where(x => x.ApplicationURL == null);

这使用LINQ的扩展方法而不是常规语法来做同样的事情。这只是个人偏好的问题。

答案 2 :(得分:1)

public partial class Course_Services
{
    #region Process All Courses Application's URL
    public List<CourseInstanceModel> ProcessAllCoursesApplicationURL(CourseApplicationsURLFeed_Model _obj)
    {

        //get all the courses which have Application URL is Null..
        using(var _uof = new Courses_UnitOfWork())
        {
          var  ListOfCoursesInstances = _uof.CourseInstances_Repository.GetAll();

          var _listOfCoursesWithoutURL = (from b in ListOfCoursesInstances 
                                           where b.ApplicationURL == null
                                           select b).ToList();


          return _listOfCoursesWithoutURL;
        }

    }
    #endregion
}