Home > database >  How do I pass the value of the FK through the Seed in asp.net project
How do I pass the value of the FK through the Seed in asp.net project

Time:10-28

I use seed to enter default data into the database, but I am facing a problem, which is the FK, How do I pass the value of FK to the two tables without any problem ?

I get this error when I run the program : SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_AspNetUsers_Departments_DepartmentId". The conflict occurred in database "HRS.WEB1", table "dbo.Departments", column 'Id'. The statement has been terminated.

 public static class DbSeeder
            {
                public static IHost SeedDb(this IHost webHost)
                {
                    using var scope = webHost.Services.CreateScope();
                    try
                    {
                        var context = scope.ServiceProvider.GetRequiredService<HRSDbContext>();
                        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<Employee>>();
                        context.SeedDepartment().Wait();
                        userManager.SeedEmployee().Wait();
        
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                    return webHost;
                }
        
                public static async Task SeedDepartment(this HRSDbContext _db)
                {
                    if (await _db.Departments.AnyAsync())
                    {
                        return;
                    }
        
                    var departments = new List<Department>();
        
                    var department = new Department();
                    department.Name = "A1";
                    department.Id = 1;
                    department.CreatedAt = DateTime.Now;
        
                    var department2 = new Department();
                    department2.Name = "A2";
                    department2.Id = 2;
                    department2.CreatedAt = DateTime.Now;
        
                    departments.Add(department);
                    departments.Add(department2);
        
                    await _db.Departments.AddRangeAsync(departments);
                    await _db.SaveChangesAsync();
                }
        
                public static async Task SeedEmployee(this UserManager<Employee> userManger)
                {
                    if (await userManger.Users.AnyAsync())
                    {
                        return;
                    }
                    var user = new Employee();
                    user.FullName = "System Developer";
                    user.UserName = "[email protected]";
                    user.Email = "[email protected]";
                    user.CreatedAt = DateTime.Now;
        
                    await userManger.CreateAsync(user, "Admin111$$");
                }
        
        
            }

CodePudding user response:

There are multiple ways to do this, I dont know the exact structure of your model but the log should be the same regardless:

First - Hard the value in:

public static async Task SeedEmployee(this UserManager<Employee> userManger)
            {
                if (await userManger.Users.AnyAsync())
                {
                    return;
                }
                var user = new Employee();
                user.FullName = "System Developer";
                user.UserName = "[email protected]";
                user.Email = "[email protected]";
                user.CreatedAt = DateTime.Now;
                user.DepartmentId = 1; //here
    
                await userManger.CreateAsync(user, "Admin111$$");
            }

Second - Return the departments you add, then pass it as parameter:

public static IHost SeedDb(this IHost webHost)
            {
                using var scope = webHost.Services.CreateScope();
                try
                {
                    var context = scope.ServiceProvider.GetRequiredService<HRSDbContext>();
                    var userManager = scope.ServiceProvider.GetRequiredService<UserManager<Employee>>();
                    var departments = context.SeedDepartment().Wait();
                    userManager.SeedEmployee(departments.First().Id ).Wait();
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw;
                }
                return webHost;
            }
    
            public static async Task<IEnumerable<Department>> SeedDepartment(this HRSDbContext _db)
            {
                var _departments = await _db.Departments.AllAsync()
                if (_departments != null)
                {
                    return _departments;
                }
    
                var departments = new List<Department>();
    
                var department = new Department();
                department.Name = "A1";
                department.Id = 1;
                department.CreatedAt = DateTime.Now;
    
                var department2 = new Department();
                department2.Name = "A2";
                department2.Id = 2;
                department2.CreatedAt = DateTime.Now;
    
                departments.Add(department);
                departments.Add(department2);
    
                await _db.Departments.AddRangeAsync(departments);
                await _db.SaveChangesAsync();

                return departments;
            }
    
            public static async Task SeedEmployee(this UserManager<Employee> userManger, int departmentId)
            {
                if (await userManger.Users.AnyAsync())
                {
                    return;
                }
                var user = new Employee();
                user.FullName = "System Developer";
                user.UserName = "[email protected]";
                user.Email = "[email protected]";
                user.CreatedAt = DateTime.Now;
                user.DepartmentId = departmentId;
    
                await userManger.CreateAsync(user, "Admin111$$");
            }
  • Related