То, что я пытаюсь сделать, этомодель передается словарем типа .Data.Entity.Infrastructure.DbQuery, но требует модель типа «System.Collections.Generic.IEnumerable
UserRoles:
public class UserRolesController : Controller
{
private HMSEntities db = new HMSEntities();
//
// GET: /UserRoles/
public ActionResult Index()
{
User user = (User)Session["User"];
var usr = db.Users.Find(user.Id);
ViewBag.Id = usr.Id;
ViewBag.FirstName = usr.FirstName;
if (Session["User"] != null)
{
var role = db.Roles.Where(u => u.Id == user.RoleId);
}
return View(usr);
}
Index.cshtml
@model IEnumerable<HMS.Models.User>
@using HMS.Models;
В этом проекте, когда пользователь входит в систему, то пользователь может просматривать свои данные, а затем выполнять операции Crud на роли этого пользователя, но я получаю сообщение об ошибке:
The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery
1[HMS.Models.Role]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
1[HMS.Models.User]'.
Мои модели являются:
Role.cs
public partial class Role
{
public Role()
{
this.Users = new HashSet<User>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
User.cs
public partial class User
{
public User()
{
this.Accesses = new HashSet<Access>();
this.Doctors = new HashSet<Doctor>();
this.Patients = new HashSet<Patient>();
this.Staffs = new HashSet<Staff>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public Nullable<int> Age { get; set; }
public Nullable<int> PhoneNo { get; set; }
public Nullable<int> LandlineNO { get; set; }
public Nullable<bool> Status { get; set; }
public string PermentAddress { get; set; }
public string TemproryAddress { get; set; }
public string BloodGroup { get; set; }
public string Gender { get; set; }
public string EducationFinal { get; set; }
public string Experience { get; set; }
public string EmailId { get; set; }
public byte[] Image { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Nullable<int> RoleId { get; set; }
public virtual ICollection<Access> Accesses { get; set; }
public virtual ICollection<Doctor> Doctors { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
public virtual Role Role { get; set; }
public virtual ICollection<Staff> Staffs { get; set; }
}
Я новичок в MVC и не знаю, что еще делать. Если требуется какой-либо дополнительный код, пожалуйста, сообщите и ответьте.
Ваш взгляд определяет имеет '@model IEnumerable' но вы контроллер имеет 'возврат View (ViewBag.role); '(почему вы все равно помещаете его в' ViewBag'), который представляет собой набор 'Role', а не' User'. Бит непонятно, что вы действительно хотите показать в представлении –
Я изменил свой код, и теперь я помещаю значение в var.Я хочу отображать данные пользователя, а также выполнять операции над ролями, но поскольку у пользователя есть ссылка на внешний ключ, я использую @model IEnumerable –
Itaws
Если вы хотите вернуть одного пользователя и их роли, тогда модели понадобится для '@model HMS.Models.User', и вам нужно будет вернуть' User' (заполненный их ролями). Трудно дать правильный код, не зная своих моделей. –