Я получаю эту ошибку, когда пытаюсь войти в свой ASP.NET MVC5 с помощью веб-приложения Identity. Это приложение было MVC4, пока я не обновился до MVC5 из-за Identity. В MVC4 он использует класс User.cs, тогда как в MVC5 мой ApplicationUser получен из IdentityUser.MVC 5 Множественные наборы объектов для каждого типа не поддерживаются
Несколько наборов объектов на тип не поддерживаются. Наборы объектов «Приложения-приложения» и «Пользователи» могут содержать экземпляры типа «Рекреационные сервисыTicketingSystem.Models.ApplicationUser».
Я читал из этого question, что мне нужно, чтобы удалить эту строку, чтобы исправить мою проблему
public System.Data.Entity.DbSet<Manager.Models.ApplicationUser> IdentityUsers { get; set; }
, но после его удаления у меня есть несколько ошибок на «ApplicationUsers» в моем ApplicationUserController.cs говоря
'ApplicationDbContext' не содержит определения для 'ApplicationUsers' и не использует метод расширения 'ApplicationUsers' принимать первый аргумент типа 'ApplicationDbContext' может быть найдено
IdentityModels.cs
namespace RecreationalServicesTicketingSystem.Models
{
public class ApplicationUser
: IdentityUser<int, ApplicationUserLogin,
ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public bool IsAdministrator { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
public string FullName
{
get { return FirstMidName + " " + LastName; }
}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() { }
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, string description)
: this(name)
{
this.Description = description;
}
}
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public class ApplicationUserStore :
UserStore<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole,
ApplicationUserClaim>, IUserStore<ApplicationUser, int>,
IDisposable
{
public ApplicationUserStore() : this(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationUserStore(DbContext context)
: base(context)
{
}
}
public class ApplicationRoleStore
: RoleStore<ApplicationRole, int, ApplicationUserRole>,
IQueryableRoleStore<ApplicationRole, int>,
IRoleStore<ApplicationRole, int>, IDisposable
{
public ApplicationRoleStore()
: base(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationRoleStore(DbContext context)
: base(context)
{
}
}
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Depot> Depots { get; set; }
public System.Data.Entity.DbSet<RecreationalServicesTicketingSystem.Models.ApplicationUser> ApplicationUsers { get; set; }
}
}
ApplicationUserController.cs
public class ApplicationUserController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: ApplicationUser
public async Task<ActionResult> Index()
{
var applicationUsers = db.ApplicationUsers.Include(a => a.Department).Include(a => a.Depot);
return View(await applicationUsers.ToListAsync());
}
// GET: ApplicationUser/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser applicationUser = await db.ApplicationUsers.FindAsync(id);
if (applicationUser == null)
{
return HttpNotFound();
}
return View(applicationUser);
}
// GET: ApplicationUser/Create
public ActionResult Create()
{
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName");
return View();
}
// POST: ApplicationUser/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,IsAdministrator,LastName,FirstMidName,EnrollmentDate,DepartmentID,DepotID,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
db.ApplicationUsers.Add(applicationUser);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", applicationUser.DepartmentID);
ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName", applicationUser.DepotID);
return View(applicationUser);
}
// GET: ApplicationUser/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser applicationUser = await db.ApplicationUsers.FindAsync(id);
if (applicationUser == null)
{
return HttpNotFound();
}
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", applicationUser.DepartmentID);
ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName", applicationUser.DepotID);
return View(applicationUser);
}
// POST: ApplicationUser/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,IsAdministrator,LastName,FirstMidName,EnrollmentDate,DepartmentID,DepotID,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
{
if (ModelState.IsValid)
{
db.Entry(applicationUser).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", applicationUser.DepartmentID);
ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName", applicationUser.DepotID);
return View(applicationUser);
}
// GET: ApplicationUser/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser applicationUser = await db.ApplicationUsers.FindAsync(id);
if (applicationUser == null)
{
return HttpNotFound();
}
return View(applicationUser);
}
// POST: ApplicationUser/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
ApplicationUser applicationUser = await db.ApplicationUsers.FindAsync(id);
db.ApplicationUsers.Remove(applicationUser);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
После того, как вы удалите эту строку, вы можете найти свойство «Пользователи» в своем контексте? Это свойство также будет 'DbSet'' ApplicationUser'. Если вы его найдете, вы можете просто использовать его в своем контроллере. –