D
D
DD-var2021-10-08 06:25:25
ASP.NET
DD-var, 2021-10-08 06:25:25

How to enable AsNoTracking EF core?

I do a check for the initial data, if they are not there, what would be added. I ran into a problem, when adding a role to a user, an error occurs:

The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

The Detach method fixed it but did not help. The service for adding users was transferred to Scoped, nothing has changed.
Services:
public static IServiceCollection InitServices(IServiceCollection services, IConfiguration configuration)
        {
           
           services.AddIdentity<User, IdentityRole>().AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationContext>();

           services.AddAutoMapper(typeof(ConfigureOfMapping));
           services.AddTransient<ConfigureOfMapping>();

           services.AddScoped(typeof(IUserService), typeof(UserService));
           services.AddTransient(typeof(IBookService), typeof(BookService));
           services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
           
           services.AddScoped<IUnitOfWork,UnitOfWorkRepo>();
            return services;
        }


Adding users and roles:
public UserRole(IUserService userService, IBookService bookService, IMapper mapper,IUnitOfWork work,IRepository<User>repository)
        {
            _userService = userService;
            _bookService = bookService;
            _mapper = mapper;
            _work = work;
            _repository = repository;
        }

        private readonly RegisterViewModel _admin = new RegisterViewModel()
        {
            Email = "[email protected]",
            FirstName = "Admin",
            Surname = "Admin",
            FullName = "AdminFull",
            Password = "Administrator",
            ConfirmPassword = "Administrator",
            UserName = "OnionAdmin"
        };

private string _adminRole = "Admin";

        public async Task CheckValue()
        {
            var admin = _mapper.Map<UserViewModel>(_admin);
//мапим пользователя
            if (await _userService.FindRole(_adminRole) == null)
            {
                await _userService.CreateRole(_adminRole);
            }
//Проверка есть ли роль и если нет создаем
            if (await _userService.FindUser(_admin.Email) == null)
            {
               await _userService.Create(_admin);
            }
//Проверка есть ли пользователь если нет создаем

            if (!await _userService.IsInRole(admin, _adminRole))
            {
                admin = _mapper.Map<UserViewModel>(await _userService.FindUser(_admin.Email) ) ;
                //получаю пользователя и его ID
                var result= await _userService.AddToRole(null, _adminRole,admin);;
           //добавление роли пользователю
            }


running code:

public static async Task Main(string[] args)
        {
           IHost webHost= CreateHostBuilder(args).Build();
           using (var scoped=webHost.Services.CreateScope())
           {
               var con = scoped.ServiceProvider.GetService<UserRole>();
               await con.CheckValue();
           }
           webHost.Run();
        }


What am I doing wrong and how to fix it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question