MVC 5不支持每种类型的多个对象集

时间:2016-03-29 03:24:58

标签: c# asp.net-mvc entity-framework asp.net-identity

当我尝试使用Identity Web Application登录ASP.NET MVC5时出现此错误。此应用程序曾经是MVC4,直到我因为Identity而升级到MVC5。在MVC4中,它使用User.cs类,而在MVC5中,我的ApplicationUser派生自IdentityUser。

  

不支持每种类型的多个对象集。对象集   'ApplicationUsers'和'Users'都可以包含类型的实例   'RecreationalServicesTicketingSystem.Models.ApplicationUser'。

我从这个question读到我需要删除此行来解决我的问题

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

但删除后我在ApplicationUserController.cs中的'ApplicationUsers'上有多个错误

  

'ApplicationDbContext'不包含的定义   'ApplicationUsers'并没有扩展方法'ApplicationUsers'   接受“ApplicationDbContext”类型的第一个参数可能是   结果

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);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您的班级代表

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

已经有Users属性

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

TUser的{​​{1}}为ApplicationUser

您需要将db.ApplicationsUsers的所有实例替换为db.Users

示例:

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

更改为:

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

答案 1 :(得分:2)

IdentityDbContext类已有一个名为DbSet<ApplicationUser>的{​​{1}}属性。

因此,如果您自己的上下文类继承自Users,则无需添加您自己的IdentityDbContext属性(事实上,如果您这样做,您将遇到“多个对象集”)误差)。

DbSet<ApplicationUser>属性将在您自己的上下文中提供,因此您可以使用它。

答案 2 :(得分:0)

当我这样做时,此视图需要两行:

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

如果我仅使用我的Rclientes,则无法使用完整视图。