2

I get this error when I try to login into my ASP.NET MVC5 with Identity Web Application. This application used to be MVC4 until I upgraded to MVC5 because of Identity. In MVC4 it uses a User.cs class while in MVC5 my ApplicationUser is derived from IdentityUser.

Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'RecreationalServicesTicketingSystem.Models.ApplicationUser'.

I read from this question that I needed to remove this line to fix my problem

public System.Data.Entity.DbSet<Manager.Models.ApplicationUser> IdentityUsers { get; set; }

but after removing it I have multiple errors on 'ApplicationUsers' in my ApplicationUserController.cs saying

'ApplicationDbContext' does not contain a definition for 'ApplicationUsers' and no extension method 'ApplicationUsers' accepting a first argument of type 'ApplicationDbContext' could be found

enter image description here

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);
        }
    }
}
Community
  • 1
  • 1
TykiMikk
  • 1,058
  • 3
  • 15
  • 31
  • 1
    After you remove that line, can you look for a `Users` property in your context? This property would be a `DbSet` of `ApplicationUser` as well. If you find it, you can just use that in your controller. – OJ Raqueño Mar 29 '16 at 03:31

3 Answers3

3

Your class representation of

public class ApplicationDbContext
    : IdentityDbContext<ApplicationUser, ApplicationRole, int,
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{...}

already has a Users property

public virtual IDbSet<TUser> Users { get; set; }

where TUser for you will be ApplicationUser.

You need to replace all instance of where you have db.ApplicationsUsers to db.Users

example:

var applicationUsers = db.ApplicationUsers.Include(a => a.Department).Include(a => a.Depot);

changes to:

var applicationUsers = db.Users.Include(a => a.Department).Include(a => a.Depot);
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • If I replace all instances of db.ApplicationUsers to db.Users then i get an error on this line `ApplicationUser applicationUser = await db.Users.FindAsync(id);` then I get `IDbSet' does not contain a defintion for 'FindAsync' and no extension method 'FindAsync' accepting a first argument of type 'IDbSet' could be found.` – TykiMikk Mar 29 '16 at 03:41
  • which is correct. IDbSet does not have that async method – Nkosi Mar 29 '16 at 03:42
  • So I need to recreate my Controllers to not have async controllers? – TykiMikk Mar 29 '16 at 03:43
  • Not necessarily. You can make your own async extension method to do it async – Nkosi Mar 29 '16 at 03:45
  • That sounds a bit too hard. I don't even know what async does. All I know is that it doesn't waste a thread waiting for another to compute data. – TykiMikk Mar 29 '16 at 03:46
2

The IdentityDbContext class already has a DbSet<ApplicationUser> property called Users.

So, if your own context class inherits from IdentityDbContext, there is no need to add your own DbSet<ApplicationUser> property (and in fact, if you do, you will encounter the "multiple object sets" error).

The Users property will be available on your own context, so you can just use that instead.

OJ Raqueño
  • 4,471
  • 2
  • 17
  • 30
  • Don't quite understand what you mean by `The Users property will be available on your own context, so you can just use that instead.` So I remove `public System.Data.Entity.DbSet ApplicationUsers { get; set; }` and use which one? – TykiMikk Mar 29 '16 at 03:37
  • It's how inheritance works. Any class that inherits from `IdentityDbContext` will have access to all of its non-private properties. The `IdentityDbContext` class has a non-private `Users` property, which is a `DbSet`. So, when you use your own context (which inherits from `IdentityDbContext`), the `Users` property will be available for your use. – OJ Raqueño Mar 29 '16 at 03:41
  • But after changing 1db.ApplicationsUsers1 to 1db.Users` I get this `IDbSet' does not contain a defintion for 'FindAsync' and no extension method 'FindAsync' accepting a first argument of type 'IDbSet' could be found` – TykiMikk Mar 29 '16 at 03:43
  • You can just use the non-async version if that's okay with you. You might want to look at using the `UserManager` class as well. – OJ Raqueño Mar 29 '16 at 03:48
  • Non-async controllers? – TykiMikk Mar 29 '16 at 03:56
0

when I do this, this view need the two new lines:

public System.Data.Entity.DbSet<Residual.Models.Residual.Rclient> Rclients { get; set; }
public System.Data.Entity.DbSet<Residual.Models.ApplicationUser> ApplicationUsers { get; set; }

and if i use only my Rclientes i couldnt use the full view.

Nick
  • 138,499
  • 22
  • 57
  • 95