Несколько наборов объектов для каждого типа не поддерживаются. Наборы объектов "ApplicationUsers" и "Users" могут содержать экземпляры типа ApplicationUser

Я застрял в странной проблеме.

Я изучаю MVC 5, и почти все создается встроенным шаблоном. Я только добавил историю класса

public class History
{
    [Key]
    public DateTime Date { get; set; }

    public virtual ApplicationUser User { get; set; }

    public string ItemName { get; set; }

}

и внутри встроенного ApplicationUser:

  public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        public virtual ICollection<History> Histories { get; set; }
    }

вот сообщение об ошибке:

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

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.InvalidOperationException: Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'MyOnlineShopping.Models.ApplicationUser'.

    Source Error: 


    Line 124:            {
    Line 125:                var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
    Line 126:                IdentityResult result = await UserManager.CreateAsync(user, model.Password);
    Line 127:                if (result.Succeeded)
    Line 128:                {
Source File: f:WorkplaceMyOnlineShoppingMyOnlineShoppingControllersAccountController.cs    Line: 126 

3 ответов


Я закончил переименование ApplicationUser в User, rescaffolding, и все волшебным образом начало работать.

похоже, шаблоны немного не в себе.


выше это просто работа вокруг, есть много ответов на эту же проблему вокруг так.

здесь

здесь

и здесь

посмотрите внутри IdentityModel.cs, вы найдете

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

внутри этого контекста VS иногда добавляет DbSet<ApplicationUser> ApplicationUsers

ЭТО ДУБЛИКАТ

внутри класса IdentityDbContext находится пользователь DbSet, когда вы подкласс из IdentityContext, наследование преобразует эту строку в DbSet<ApplicationUser> User.

исправить? Удалить DbSet<ApplicationUser> User С public class ApplicationDbContext : IdentityDbContext<ApplicationUser>


эта ошибка происходит, когда ваш ApplicationDbContext класс изменился. просто сделайте это в папку "модели" и перейдите в IdentityModels.cs class и удалить последнюю строку

public System.Data.Entity.DbSet < Project.Models.ApplicationUserProject.Models.ApplicationUser> ApplicationUsers { get; set; }

эта строка генерируется автоматически scaffold.