【问题标题】:LINQ to entities against EF in many to many relationship多对多关系中针对 EF 的实体的 LINQ
【发布时间】:2013-02-02 11:29:36
【问题描述】:

我正在使用 ASP.NET MVC4 EF CodeFirst。

需要帮助在索引操作中编写 LINQ(到实体)代码,以获取所选学生参加的课程的集合。 连接表与负载的关系是多对多的。

//StudentController
//-----------------------

public ActionResult Index(int? id)
{
    var viewModel = new StudentIndexViewModel();
    viewModel.Students = db.Students;

    if (id != null)
    {
        ViewBag.StudentId = id.Value;
        // *************PROBLEM IN LINE DOWN. HOW TO MAKE COURSES COLLECTION? 
        viewModel.Courses = db.Courses
            .Include(i => i.StudentsToCourses.Where(t => t.ObjStudent.FkStudentId == id.Value));
    }


    return View(viewModel);
}

我得到的错误是:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

我有模型(第三个是用于连接有效负载的表):

//MODEL CLASSES
//-------------

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }

    public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; }
}

public class StudentToCourse
{
    public int StudentToCourseId { get; set; }
    public int FkStudentId { get; set; }
    public int FkCourseId { get; set; }
    public string Classroom { get; set; }

    public virtual Student ObjStudent { get; set; }
    public virtual Course ObjCourse { get; set; }
}

然后,这是我需要传递给视图的模型视图

//VIEWMODEL CLASS
//---------------

public class StudentIndexViewModel
{
    public IEnumerable<Student> Students { get; set; }
    public IEnumerable<Course> Courses { get; set; }
    public IEnumerable<StudentToCourse> StudentsToCourses { get; set; }
}

【问题讨论】:

    标签: asp.net-mvc linq linq-to-entities entity-framework-5


    【解决方案1】:

    EF 不支持条件包含。您需要包含全部或全部内容(即在 Include 中不包含 Where

    如果您只需要获取某些关系的数据,您可以将其选择为匿名类型,例如(显然未经测试);

    var intermediary = (from course in db.Courses
                        from stc in course.StudentsToCourses
                        where stc.ObjStudent.FkStudentId == id.Value
                        select new {item, stc}).AsEnumerable();
    

    显然,这将需要更改一些代码,因为它不再是带有 StudentToCourses 集合的直接课程。

    【讨论】:

    • 谢谢!我正在考虑使用 ViewBag 将中间变量传递给查看。也许“AsNumerable()”应该替换为“ToList()”?你有什么看法?
    • @Branislav AsEnumerable() 可以替换为ToList(),是的。唯一的缺点是如果您继续对结果进行过滤,其中创建 List() 可能是不必要的开销,应该在应用所有过滤器后完成。
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2021-10-21
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2021-06-10
    相关资源
    最近更新 更多