简体   繁体   English

使用linq从两个表(联接)中获取数据并将结果返回到视图中

[英]Get data from two tables(join) with linq and return result into view

I want to get data from Projects(which have CourseId) and related CourseName from Courses table. 我想从Projects(具有CourseId)中获取数据,并从Courses表中获取相关的CourseName。

I have written following code: 我写了以下代码:

var projects = from n in db.Projects
                       join c in db.Courses on n.CourseId equals c.ID
                       orderby n.Name
                       select new { Project = n, Course = c };

        return View(projects.ToList());

and I get error: 我得到错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[<>f__AnonymousType2 2[ProjectManager.Models.Project,ProjectManager.Models.Course]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ProjectManager.Models.Project]'. 传递到字典中的模型项的类型为'System.Collections.Generic.List 1[<>f__AnonymousType2 2 [ProjectManager.Models.Project,ProjectManager.Models.Course]]',但是此字典需要类型为'的模型项System.Collections.Generic.IEnumerable`1 [ProjectManager.Models.Project]'。

What I need to do in Controller and in View to display this data? 我需要在Controller和View中显示这些数据吗?

You're passing an anonymous type into your view, but the view is declared as taking an IEnumerable<Project> . 您正在向视图中传递匿名类型,但是该视图被声明为采用IEnumerable<Project>

You should remove the @model declaration from the view to make it use a dynamic model. 您应该从视图中删除@model声明,以使其使用dynamic模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM