我正在尝试在我的 asp.net mvc
项目的同一个视图中使用两个表,但我犯了一些错误并收到此错误:
System.InvalidOperationException: 传入字典的模型项的类型为“System.Data.Entity.Infrastructure.DbQuery1[Question]
,但此字典需要类型为“System.Collections.Generic.IEnumerable”的模型项1[projet.Models.userdbcontext]
Questions.cs
类:
public class Question
{
public int Id { get; set; }
public int userID { get; set; }
}
User.cs
类:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
}
模型 userdbcontext.cs
:
{
public userdbcontext()
{ }
public DbSet<Question> Questiondb { get; set; }
public DbSet<User> Usersdb { get; set; }
}
这是控制器:
private userdbcontext db = new userdbcontext();
// GET: question
public ActionResult Index()
{
var l = from e in db.Questiondb
select e;
return View(l);
}
视图:
@model IEnumerable<projet.Models.userdbcontext>
答案 0 :(得分:2)
你必须创建一个视图模型:
public class ViewModel
{
public List<Question> Questions { get; set; }
public List<User> Users { get; set; }
}
动作
public ActionResult Index()
{
var vm = new ViewModel{
Questions = db.Questiondb.ToList(),
Users= db.Userdb.ToList()
}
return View(vm);
}
查看
@model projet.Models.ViewModel
....
<!-- Accessing Model Variables -->
@Model.Questions...
@Model.Users...
答案 1 :(得分:1)
您的错误是您试图将 DbSet<>
发送到难以操作的视图,因此要解决问题,您必须创建一个新类 ViewModel
来存储值DbSet<>
作为 List<>
然后你把它传递给 View 像这样:
模型 userdbcontext.cs:
public class userdbcontext : DbContext
{
public userdbcontext()
{ }
public DbSet<Question> Questiondb { get; set; }
public DbSet<User> Usersdb { get; set; }
}
public class ViewModel
{
public List<Question> Question { get; set; }
public List<User> User { get; set; }
}
在控制器中:
private userdbcontext db = new userdbcontext();
// GET: question
public ActionResult Index()
{
var l = new ViewModel();
l.Question = db.Questiondb.ToList();
l.User = db.Usersdb.ToList();
return View(l);
}
并在视图中:
@model projet.Models.ViewModel