Visual Studio 2012 Internet应用MVC4 C#
错误
System.InvalidOperationException:传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery 1, but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1
我的视图期望:@model IEnumerable<OG.Models.UserProfiles>
这是dataModel而不是ViewModel。 *当我创建控制器时,此视图也是UserProfiles
模型生成的一个视图(使用@Html.DisplayNameFor(model => model.Company)
的Standart脚手架,后来使用@foreach (var item in Model) {
列出数据)
我的控制器尝试:
尝试1次感知(不返回列表)
return View(db.UserProfiles
.Include(c => c.Roles)
.Where(c => c.Roles.Any(up => up.RoleName != "Administrator"))
.Select(c => new
{
UserID = c.UserID,
UserName = c.UserName,
UserCount = c.Roles.Count()
}));
尝试2意识(不返回列表)
var model =
from usr in db.UserProfiles
join rls in db.UserRoles on usr.Roles equals rls.RoleId
select new { UserID = usr.UserID, UserName = usr.UserName };
尝试3感知(不返回列表)
var model =
from usr in db.UserProfiles.Include(t => t.Roles)
where usr.Roles.Any(up => up.RoleName != "Administrator")
select new WebAdminUsersLookup
{
UserID = usr.UserID,
UserName = usr.UserName
};
尝试4猜这不是一个“真实”列表,仍然存在错误
var listOfIdeas =
(from x in db.UserProfiles.Include(t => t.Roles)
.Where(u => u.Roles.Any(up => up.RoleName != "Administrator"))
select new { UserID = x.UserID, UserName = x.UserName }).ToList();
尝试1-3
List<UserProfiles> modelList = new List<UserProfiles>();
modelList.Add(model.ToList());
这样的东西,并为他们创建了一个Viewmodel
private class WebAdminUsersLookup
{
//public List<UserProfiles> Users { get; set; }
public int UserID { get; set; }
public string UserName { get; set;}
}
搜索的网站:
This Stack Overflow Q&A
And this one
and this one
最佳答案
如果您的视图需要IEnumerable<OG.Models.UserProfiles>
,则应传递给它,而不是传递给LINQ查询中的某些匿名对象。如果IEnumerable<OG.Models.UserProfiles>
不足以容纳您的视图,并且您需要其他信息,那么最好创建一个视图模型:
public class MyViewModel
{
public int UserID { get; set; }
public string UserName { get; set; }
public int RolesCount { get; set; }
}
然后在此视图模型上进行投影:
IEnumerable<MyViewModel> model = db
.UserProfiles
.Include(c => c.Roles)
.Where(c => c.Roles.Any(up => up.RoleName != "Administrator"))
.Select(c => new MyViewModel
{
UserID = c.UserID,
UserName = c.UserName,
RolesCount = c.Roles.Count()
});
return View(model);
最后,将您的视图强类型化为与您在控制器操作中传递的视图相同的模型:
@model IEnuemrable<MyViewModel>
关于asp.net-mvc - Linq查看错误,传递通用列表:必需IEnumerable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18383738/