C# 实体类型ApplicationUser不是当前上下文、DB First和自定义用户存储的模型的一部分

C# 实体类型ApplicationUser不是当前上下文、DB First和自定义用户存储的模型的一部分,c#,mysql,entity-framework,asp.net-mvc-5,asp.net-identity,C#,Mysql,Entity Framework,Asp.net Mvc 5,Asp.net Identity,因此,我正在现有数据库的基础上构建一个应用程序,我对该数据库的更改权限有限(想法是尽可能少地更改DB模式)。这是一个MVC5应用程序,它试图将身份系统与自定义用户存储一起使用到MySQL数据库 问题:我在尝试通过register方法中自动生成的AccountController注册用户时遇到以下异常: IdentityResult result = await UserManager.CreateAsync(user, model.Password); System.InvalidOpera

因此,我正在现有数据库的基础上构建一个应用程序,我对该数据库的更改权限有限(想法是尽可能少地更改DB模式)。这是一个MVC5应用程序,它试图将身份系统与自定义用户存储一起使用到MySQL数据库

问题:我在尝试通过register方法中自动生成的AccountController注册用户时遇到以下异常:

IdentityResult result = await UserManager.CreateAsync(user, model.Password); 
System.InvalidOperationException:实体类型ApplicationUser不是当前上下文的模型的一部分。 位于System.Data.Entity.Internal.InternalContext.UpdateEntityMatpingsForType(类型entityType) 位于System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(类型entityType) 在System.Data.Entity.Internal.Linq.InternalSet
1.Initialize()处
位于System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext() 在System.Data.Entity.Infrastructure.DbQuery
1.System.Linq.IQueryable.get_Provider()中
位于System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable
1源,表达式
1谓词,CancellationToken CancellationToken)
位于System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable
1源,表达式
1谓词)
在Microsoft.AspNet.Identity.EntityFramework.UserStore上

我所尝试的:

  • 我已尝试从更改帐户控制器的UserManager实例化
    HttpContext.GetOwinContext()

    DbContext设置(我已从自动生成的文件中修改,以尝试使用标识系统):

    public分部类实体:IdentityDbContext//DbContext
    {
    公共实体()
    :base(“名称=实体”)
    {
    }
    模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
    {
    抛出新代码FirstException();
    }
    公共静态实体创建()
    {
    返回新实体();
    }
    //DBSET在这里
    }
    
    ApplicationUser.cs:

    public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim> // IUser<int>//IdentityUser
    {
        //custom properties are here
    
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
        {
    
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here            
    
            return userIdentity;
        }
    }
    
    公共类应用程序用户:IdentityUser//IUser//IdentityUser
    {
    //自定义属性在这里
    公共异步任务GenerateUserIdentityAsync(用户管理器)
    {
    var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
    //在此处添加自定义用户声明
    返回用户身份;
    }
    }
    
    ApplicationUserManager.cs

    public class ApplicationUserManager : UserManager<ApplicationUser, int>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
            : base(store)
        { }
    
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStoreService(context.Get<Entities>()));
    
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
    
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
    
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;
    
            manager.EmailService = new EmailService();
    
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity")) { TokenLifespan = TimeSpan.FromHours(24) };
            }
            return manager;
        }
    }
    
    公共类应用程序管理员:用户管理员
    {
    公共应用程序服务器管理器(IUserStore存储)
    :基地(商店)
    { }
    公共静态应用程序SerManager创建(IdentityFactoryOptions选项,IOwinContext上下文)
    {
    var manager=newapplicationUserManager(newuserstoreservice(context.Get());
    //为用户名配置验证逻辑
    manager.UserValidator=新的UserValidator(管理器)
    {
    AllowOnlyAlphanumericUserNames=false,
    RequireUniqueEmail=true
    };
    //配置密码的验证逻辑
    manager.PasswordValidator=新密码验证器
    {
    所需长度=6,
    RequiredOnletterDigit=真,
    RequireDigit=true,
    RequireLowercase=true,
    RequireUppercase=true,
    };
    manager.UserLockoutEnabledByDefault=true;
    manager.DefaultAccountLockoutTimeSpan=TimeSpan.FromMinutes(5);
    manager.MaxFailedAccessAttemptsBeforeLockout=5;
    manager.EmailService=新的EmailService();
    var dataProtectionProvider=options.dataProtectionProvider;
    if(dataProtectionProvider!=null)
    {
    manager.UserTokenProvider=
    新的DataProtectorTokenProvider(dataProtectionProvider.Create(“ASP.NET标识”){TokenLifespan=TimeSpan.FromHours(24)};
    }
    退货经理;
    }
    }
    
    UserStoreService.cs

     public class UserStoreService : UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim> //, IUserStore<ApplicationUser, int>, IUserPasswordStore<ApplicationUser, int>, IUserEmailStore<ApplicationUser, int>, IUserLockoutStore<ApplicationUser, int>, IUserSecurityStampStore<ApplicationUser, int>
    {
        private Entities _db; // = new Entities();
    
        public UserStoreService(Entities db) : base(db)
        {
            _db = db;
        }
    
        public override Task CreateAsync(ApplicationUser user)
        {
            var profile = new ffs_profile {
                //set props here
            };
    
            _db.ffs_profile.Add(profile);
            return _db.SaveChangesAsync();
        }
    
        public async override Task<ApplicationUser> FindByNameAsync(string userName)
        {
            var profile = await _db.ffs_profile.Where(u => u.email == userName).FirstOrDefaultAsync();
    
            ApplicationUser user = null;
            if (profile != null)
                user = ToApplicationUser(profile);
    
            return user;
        }
    
        private ApplicationUser ToApplicationUser(ffs_profile profile)
        {
            return new ApplicationUser
            {
               //set properties here
    
            };
        }
        public override Task<string> GetPasswordHashAsync(ApplicationUser user)
        {
            if (user == null)
            {
                throw new ArgumentException("null user");
            }
    
            return Task.FromResult(user.PasswordHash);
        }
    
        public override Task<bool> HasPasswordAsync(ApplicationUser user)
        {
            return Task.FromResult(user.PasswordHash != null);
        }
    
        public override Task SetPasswordHashAsync(ApplicationUser user, string passwordHash)
        {
            return Task.Run(() =>
            {
                if (passwordHash == null)
                    throw new ArgumentNullException("passwordHash");
                if (string.IsNullOrWhiteSpace(passwordHash))
                    throw new ArgumentException("passwordHash cannot be null, empty, or consist of whitespace.");
                 user.PasswordHash = passwordHash;
    
            });
        }
    
        public override async Task<ApplicationUser> FindByIdAsync(int userId)
        {
            var profile = await _db.ffs_profile.Where(u => u.profile_id == userId).FirstOrDefaultAsync();
    
            ApplicationUser user = null;
            if (profile != null)
                user = ToApplicationUser(profile);
    
            return user;
        }
    
        public override Task<string> GetSecurityStampAsync(ApplicationUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            return Task.FromResult<string>(user.SecurityStamp);
        }
        public override Task SetSecurityStampAsync(ApplicationUser user, string stamp)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            user.SecurityStamp = stamp;
            return Task.FromResult<int>(0);
        }
    }
    
    公共类UserStoreService:UserStore//、IUserStore、IUserPasswordStore、IUserEmailStore、IUserLockoutStore、IUserSecurityStampStore
    {
    私有实体_db;//=新实体();
    公共用户存储服务(实体数据库):基本(数据库)
    {
    _db=db;
    }
    公共覆盖任务CreateAync(ApplicationUser用户)
    {
    var配置文件=新的ffs\U配置文件{
    //在这里设置道具
    };
    _db.ffs_profile.Add(profile);
    返回_db.SaveChangesAsync();
    }
    公共异步覆盖任务FindByNameAsync(字符串用户名)
    {
    var profile=await_db.ffs_profile.Where(u=>u.email==userName).FirstOrDefaultAsync();
    ApplicationUser用户=null;
    if(profile!=null)
    用户=应用程序用户(配置文件);
    返回用户;
    }
    专用应用程序服务器到应用程序服务器(ffs\U配置文件)
    {
    返回新的应用程序用户
    {
    //在此处设置属性
    };
    }
    公共覆盖任务GetPasswordHashAsync(ApplicationUser用户)
    {
    if(user==null)
    {
    抛出新ArgumentException(“空用户”);
    }
    返回Task.FromResult(user.PasswordHash);
    }
    公共覆盖任务HasPasswordAsync(ApplicationUser用户)
    {
    返回Task.FromResult(user.PasswordHash!=null);
    }
    公共覆盖任务SetPasswordHashAsync(ApplicationUser用户,字符串passwordHash)
    {
    返回任务。运行(()=>
    {
    if(passwordHash==null)
    抛出新ArgumentNullException(“passwordHash”);
    if(string.IsNullOrWhiteSpace(passwordHash))
    抛出新ArgumentException(“passwordHash不能为null、空或由空格组成”);
    user.Pas
    
     public class UserStoreService : UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim> //, IUserStore<ApplicationUser, int>, IUserPasswordStore<ApplicationUser, int>, IUserEmailStore<ApplicationUser, int>, IUserLockoutStore<ApplicationUser, int>, IUserSecurityStampStore<ApplicationUser, int>
    {
        private Entities _db; // = new Entities();
    
        public UserStoreService(Entities db) : base(db)
        {
            _db = db;
        }
    
        public override Task CreateAsync(ApplicationUser user)
        {
            var profile = new ffs_profile {
                //set props here
            };
    
            _db.ffs_profile.Add(profile);
            return _db.SaveChangesAsync();
        }
    
        public async override Task<ApplicationUser> FindByNameAsync(string userName)
        {
            var profile = await _db.ffs_profile.Where(u => u.email == userName).FirstOrDefaultAsync();
    
            ApplicationUser user = null;
            if (profile != null)
                user = ToApplicationUser(profile);
    
            return user;
        }
    
        private ApplicationUser ToApplicationUser(ffs_profile profile)
        {
            return new ApplicationUser
            {
               //set properties here
    
            };
        }
        public override Task<string> GetPasswordHashAsync(ApplicationUser user)
        {
            if (user == null)
            {
                throw new ArgumentException("null user");
            }
    
            return Task.FromResult(user.PasswordHash);
        }
    
        public override Task<bool> HasPasswordAsync(ApplicationUser user)
        {
            return Task.FromResult(user.PasswordHash != null);
        }
    
        public override Task SetPasswordHashAsync(ApplicationUser user, string passwordHash)
        {
            return Task.Run(() =>
            {
                if (passwordHash == null)
                    throw new ArgumentNullException("passwordHash");
                if (string.IsNullOrWhiteSpace(passwordHash))
                    throw new ArgumentException("passwordHash cannot be null, empty, or consist of whitespace.");
                 user.PasswordHash = passwordHash;
    
            });
        }
    
        public override async Task<ApplicationUser> FindByIdAsync(int userId)
        {
            var profile = await _db.ffs_profile.Where(u => u.profile_id == userId).FirstOrDefaultAsync();
    
            ApplicationUser user = null;
            if (profile != null)
                user = ToApplicationUser(profile);
    
            return user;
        }
    
        public override Task<string> GetSecurityStampAsync(ApplicationUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            return Task.FromResult<string>(user.SecurityStamp);
        }
        public override Task SetSecurityStampAsync(ApplicationUser user, string stamp)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            user.SecurityStamp = stamp;
            return Task.FromResult<int>(0);
        }
    }
    
     public class AccountController : Controller
    {
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;
    
        public AccountController()
        {
        }
    
        public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }
    
        public ApplicationUserManager UserManager
        {
            get
            {   
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); 
            }
            private set
            {
                _userManager = value;
            }
        }
    // other autogenerated methods
    [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                    {
                    //set props here
                };
                try
                {
                    IdentityResult result = await UserManager.CreateAsync(user, model.Password); 
                    if (result.Succeeded)
                    {
    
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    
    
                        return RedirectToAction("Index", "Home");
                    }
                    AddErrors(result);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex.ToString());
                }
    
            }
            return View(model);
        }
    }