Open Closed

Filter name MustHaveTenant not found #201


0
codemonkey21 created

I created my project as a MPA site, then added in Zero following the instructions here: http://www.aspnetboilerplate.com/Pages/ ... stallation

Ran all appropriate migrations and seed methods.

I then created an AngularJS admin app. I created a UserAppService with GetUsers() and tested in the console like demoed here: http://www.aspnetzero.com/Documents/Dev ... er-console

This is where I first got the error for MustHaveTenant. So I assumed it was because I wasn't logging in. I went to the login form and on the LoginAsync method, I get the "Filter name MustHaveTenant not Found" exception when the method _userManager.LoginAsync() runs and trying to login as 'admin' / '123qwe'.

I've read every document 10x now and cannot figure out why this happening.

[HttpPost]
        public async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "")
        {
            if (!ModelState.IsValid)
            {
                throw new UserFriendlyException("Your form is invalid!");
            }

                var loginResult = await _userManager.LoginAsync(
                    loginModel.UsernameOrEmailAddress,
                    loginModel.Password,
                    loginModel.TenancyName
                    );

                switch (loginResult.Result)
                {
                    case AbpLoginResultType.Success:
                        break;
                    case AbpLoginResultType.InvalidUserNameOrEmailAddress:
                    case AbpLoginResultType.InvalidPassword:
                        throw new UserFriendlyException("Invalid user name or password!");
                    case AbpLoginResultType.InvalidTenancyName:
                        throw new UserFriendlyException("No tenant with name: " + loginModel.TenancyName);
                    case AbpLoginResultType.TenantIsNotActive:
                        throw new UserFriendlyException("Tenant is not active: " + loginModel.TenancyName);
                    case AbpLoginResultType.UserIsNotActive:
                        throw new UserFriendlyException("User is not active: " + loginModel.UsernameOrEmailAddress);
                    case AbpLoginResultType.UserEmailIsNotConfirmed:
                        throw new UserFriendlyException("Your email address is not confirmed!");
                    default: //Can not fall to default for now. But other result types can be added in the future and we may forget to handle it
                        throw new UserFriendlyException("Unknown problem with login: " + loginResult.Result);
                }

                AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = loginModel.RememberMe }, loginResult.Identity);


            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Request.ApplicationPath;
            }

            return Json(new MvcAjaxResponse { TargetUrl = returnUrl });
        }

3 Answer(s)
  • 0
    codemonkey21 created

    I think this is obviously related...

    I had to make some changes to my user entity and since I had no data, I basically dropped my database and migrations, created a new initial migration with all my existing entities and ran the script with seed method.

    I know get the following error on the CreateUserAndRoles() method when trying to create the second admin for the Default Tenant.

    This is all from the instructions for manual install of Zero to a project.

    No pending explicit migrations. Running Seed method. System.Data.Entity.Validation.DbEntityValidationException: Can not set TenantId to a different value from the current filter parameter value while MayHaveTenant filter is enabled! at Abp.EntityFramework.AbpDbContext.CheckMayHaveTenant(DbEntityEntry entry) at Abp.EntityFramework.AbpDbContext.CheckAndSetTenantIdProperty(DbEntityEntry entry) at Abp.EntityFramework.AbpDbContext.ApplyAbpConcepts() at Abp.EntityFramework.AbpDbContext.SaveChanges() at Nyxly.Migrations.DefaultTenantRoleAndUserBuilder.CreateUserAndRoles() in c:\MyProjects\Nyxly_ABP_6.3\src\Nyxly.EntityFramework\Migrations\DefaultTenantRoleAndUserBuilder.cs:line 107 at Nyxly.Migrations.DefaultTenantRoleAndUserBuilder.Build() in c:\MyProjects\Nyxly_ABP_6.3\src\Nyxly.EntityFramework\Migrations\DefaultTenantRoleAndUserBuilder.cs:line 27 at Nyxly.Migrations.Configuration.Seed(NyxlyDbContext context) in c:\MyProjects\Nyxly_ABP_6.3\src\Nyxly.EntityFramework\Migrations\Configuration.cs:line 19 at System.Data.Entity.Migrations.DbMigrationsConfiguration1.OnSeed(DbContext context) at System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase() at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.

    Here is my seed method

    protected override void Seed(Nyxly.EntityFramework.NyxlyDbContext context)
            {
                // This method will be called every time after migrating to the latest version.
                // You can add any seed data here...
                context.DisableAllFilters();
                new DefaultTenantRoleAndUserBuilder(context).Build();
            }
    
    private void CreateUserAndRoles()
            {
                //Admin role for tenancy owner
    
                var adminRoleForTenancyOwner = _context.Roles.FirstOrDefault(r => r.TenantId == null && r.Name == "Admin");
                if (adminRoleForTenancyOwner == null)
                {
                    adminRoleForTenancyOwner = _context.Roles.Add(new Role { Name = "Admin", DisplayName = "Admin" });
                    _context.SaveChanges();
                }
    
                //Admin user for tenancy owner
    
                var adminUserForTenancyOwner = _context.Users.FirstOrDefault(u => u.TenantId == null && u.UserName == "admin");
                if (adminUserForTenancyOwner == null)
                {
                    adminUserForTenancyOwner = _context.Users.Add(
                        new User
                        {
                            TenantId = null,
                            UserName = "admin",
                            Name = "System",
                            Surname = "Administrator",
                            EmailAddress = "admin@aspnetboilerplate.com",
                            IsEmailConfirmed = true,
                            Password = "AM4OLBpptxBYmM79lGOX9egzZk3vIQU3d/gFCJzaBjAPXzYIK3tQ2N7X4fcrHtElTw==" //123qwe
                        });
    
                    _context.SaveChanges();
    
                    _context.UserRoles.Add(new UserRole(adminUserForTenancyOwner.Id, adminRoleForTenancyOwner.Id));
    
                    _context.SaveChanges();
                }
    
                //Default tenant
    
                var defaultTenant = _context.Tenants.FirstOrDefault(t => t.TenancyName == "Default");
                if (defaultTenant == null)
                {
                    defaultTenant = _context.Tenants.Add(new Tenant { TenancyName = "Default", Name = "Default" });
                    _context.SaveChanges();
                }
    
                //Admin role for 'Default' tenant
    
                var adminRoleForDefaultTenant = _context.Roles.FirstOrDefault(r => r.TenantId == defaultTenant.Id && r.Name == "Admin");
                if (adminRoleForDefaultTenant == null)
                {
                    adminRoleForDefaultTenant = _context.Roles.Add(new Role { TenantId = defaultTenant.Id, Name = "Admin", DisplayName = "Admin" });
                    _context.SaveChanges();
                }
    
                //Admin for 'Default' tenant
    
                var adminUserForDefaultTenant = _context.Users.FirstOrDefault(u => u.TenantId == defaultTenant.Id && u.UserName == "admin");
                if (adminUserForDefaultTenant == null)
                {
                    adminUserForDefaultTenant = _context.Users.Add(
                        new User
                        {
                            TenantId = defaultTenant.Id,
                            UserName = "admin",
                            Name = "System",
                            Surname = "Administrator",
                            EmailAddress = "admin@aspnetboilerplate.com",
                            IsEmailConfirmed = true,
                            Password = "AM4OLBpptxBYmM79lGOX9egzZk3vIQU3d/gFCJzaBjAPXzYIK3tQ2N7X4fcrHtElTw==" //123qwe
                        });
                    _context.SaveChanges();
    
                    _context.UserRoles.Add(new UserRole(adminUserForDefaultTenant.Id, adminRoleForDefaultTenant.Id));
                    _context.SaveChanges();
                }
            }
    
  • 0
    hikalkan created

    "FILTER NAME MUSTHAVETENANT NOT FOUND" occurs if you overrided onmodelcreating or initialize method of your dbcontext and not called base method. Can you check it?

    When you call context.DisableAllFilters(); you don't get "Can not set TenantId to a different value from the current filter parameter value while MayHaveTenant filter is enabled" error normally.

  • 0
    codemonkey21 created

    Bah! I knew it was going to be something simple. Yes, I had made modifications and forgot to call the base...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.ComplexType<Address>();
                modelBuilder.Configurations.Add(new CategoryTypeMap());
                modelBuilder.Configurations.Add(new CountryCodeTypeMap());
                modelBuilder.Configurations.Add(new PointsLocationTypeMap());
                modelBuilder.Configurations.Add(new UserActivityTypeMap());
                modelBuilder.Configurations.Add(new UserCheckInTypeMap());
                modelBuilder.Configurations.Add(new UserImageTypeMap());
                modelBuilder.Configurations.Add(new UserPointsTypeMap());
            }