无法访问已处置的对象。 .NET核心

问题描述 投票:-2回答:1

我在这一行得到了这个错误:

var removeRole = await _userManager.RemoveFromRolesAsync(applicationUser, roles);

这是代码:

public async Task SaveClient(UserViewModel viewModel)
{
    try
    {
        var applicationUser = await DbSet.SingleOrDefaultAsync(x => x.Id == viewModel.Id && !x.Deleted);
        if (applicationUser == null) throw new Exception("User not found. ");

        var roles = await _userManager.GetRolesAsync(applicationUser);

        if (!(await _userManager.IsInRoleAsync(applicationUser, viewModel.Role)))
        {
            var removeRole = await _userManager.RemoveFromRolesAsync(applicationUser, roles);
            var addRole = await _userManager.AddToRoleAsync(applicationUser, viewModel.Role);

            if (viewModel.Role.Equals("Agente") && applicationUser.AgentId == null)
                viewModel.AgentId = "A" + new Random().Next(999) + new Random().Next(999);
        }

        Mapper.Map(viewModel, applicationUser);

        await Edit(applicationUser);

        // return Task.CompletedTask;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message + " User not found. ");
    }
}

我已尝试在“var applicationUser”行上“使用”但仍然没有运气。

有帮助吗?

这是我的启动类服务:

public void ConfigureServices(IServiceCollection services)
     {
         services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
         services.AddIdentity<ApplicationUser, IdentityRole>(config => {
                    config.SignIn.RequireConfirmedEmail = true;
         }).AddEntityFrameworkStores<ApplicationDbContext>()
           .AddDefaultTokenProviders();
            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();
            services.AddTransient<IUserRepository, UserRepository>();
            services.AddTransient<IInvestmentRepository, InvestmentRepository>();
            services.AddTransient<IProjectRepository, ProjectRepository>();
            services.AddTransient<IPortfolioRepository, PortfolioRepository>();
            services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<IPaypalRepository, PaypalRepository>();
            services.AddTransient<IStripeRepository, StripeRepository>();
            services.AddTransient<IOrderRepository, OrderRepository>();
            services.AddTransient<IComissionRepository, ComissionRepository>();
            services.AddTransient<IWithdrawRepository, WithdrawRepository>();
            services.AddTransient<IDepositRepository, DepositRepository>();
            services.AddAutoMapper();
            services.AddDistributedMemoryCache();
            services.AddSession();
            services.AddCors();
            services.AddMvc();
        }
c# asp.net-core entity-framework-core
1个回答
1
投票

我最后修改了它:

var applicationUser = await DbSet.SingleOrDefaultAsync(x => x.Id == viewModel.Id && !x.Deleted);
 if (applicationUser == null) throw new Exception("User not found. ");

对此:

var applicationUser = _userManager.FindByIdAsync(viewModel.Id).Result;
if (applicationUser == null || applicationUser.Deleted) throw new Exception("User not found. ");

也从使用async / await切换到Result。

这是整个代码:

public Task SaveClient(UserViewModel viewModel)
    {
        try
        {
            var applicationUser = _userManager.FindByIdAsync(viewModel.Id).Result;
            if (applicationUser == null || applicationUser.Deleted) throw new Exception("User not found. ");

            var role = _userManager.GetRolesAsync(applicationUser).Result.FirstOrDefault();

            if (role != viewModel.Role)
            {
                var removeRole = _userManager.RemoveFromRoleAsync(applicationUser, role).Result;
                var addRole = _userManager.AddToRoleAsync(applicationUser, viewModel.Role).Result;

                if (viewModel.Role.Equals("Agente") && applicationUser.AgentId == null)
                    viewModel.AgentId = "A" + new Random().Next(999) + new Random().Next(999);

            }

            Mapper.Map(viewModel, applicationUser);

            Edit(applicationUser);

            return Task.CompletedTask;

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message + " User not found. ");
        }
    }

我希望这可以帮助那些在另一篇文章中找不到答案的人。

© www.soinside.com 2019 - 2024. All rights reserved.