尝试显示2个表,人员和部门的值,所以我尝试执行linq sql查询但是当我在Web浏览器中打开我的应用程序时它不起作用。 MVC的新手,这是我第一次使用linq到sql所以我不确定什么是错的!
我的错误:
传递到字典中的模型项的类型为'System.Collections.Generic.List
1[<>f__AnonymousType7
4 [System.String,System.String,StaffDetails.Models.Department,StaffDetails.Models.Site]]' ,但是这个字典需要一个'System.Collections.Generic.IEnumerable`1 [StaffDetails.Models.Staff]'类型的模型项。
索引视图
public ActionResult Index()
{
IList<Staff> staffList = new List<Staff>();
var query = (from s in db.Staffs
from d in db.Departments
where s.DeptID == d.DeptID
select new
{
name = s.Name,
email = s.Email,
department = s.Department,
site = d.Site
}
).ToList();
return View(query);
}
表
答案 0 :(得分:3)
问题是您传递的是匿名类型,但您的视图需要IEnumerable<Staff>
,因此在投影LINQ
查询时,您需要投射Staff
这样的类型: -
List<Staff> query = (from s in db.Staffs
from d in db.Departments
where s.DeptID == d.DeptID
select new Staff //here
{
Name = s.Name,
Email= s.Email,
Department = s.Department,
Site = d.Site
}).ToList();
<强>更新强>
好的,所以你的Staff
是一个映射的实体,因此在这种情况下你不应该直接映射它。您需要DTO
或者您可以首先投影匿名类型并使用AsEnumerable()
将操作带到linq到对象中,然后从那里进行投影: -
IEnumerable<Staff> staffList = (from s in db.Staffs
from d in db.Departments
where s.DeptID == d.DeptID
select new
{
name = s.Name,
email = s.Email,
department = s.Department,
site = d.Site
}).AsEnumerable()
.Select(x => new new Staff
{
Name = x.name,
Email= x.email,
Department = x.department,
Site = x.site
});