Search code examples
c#asp.net-core-mvc

ASP.NET Core 6 MVC data seeder not populating categories


In the code below the AppUser and the Contact are being created, but the Category is not. The error in the terminal is...

null value in column "AppUserId" of relation "Categories" violates not-null constraint

It is a Postgresql db with a one to many of AppUser to Contact, and AppUser to Category. I can create a category in the app ok, and it shows both the Name and AppUser fields populated correctly, but for some reason the seeder isn't doing that.

This is strange since the AppUserId is correctly populated for the contact record. I can't understand why it would not do the same for the Category record. Any ideas?

Here is the code:

using ContactPro.Data;
using ContactPro.Models;
using Microsoft.AspNetCore.Identity;

namespace ContactPro.Helpers
{
    public class DataSeeder
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly UserManager<AppUser> _userManager;

        private static string appUserId;

        public DataSeeder(ApplicationDbContext dbContext, UserManager<AppUser> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }

        public async Task SeedDataAsync()
        {
            await SeedUsersAsync();
            await SeedContactsAsync();
            await SeedCategoriesAsync();
        }

        private async Task SeedUsersAsync()
        {
            if (_dbContext.Users.Any())
            {
                return;
            }

            var demoUser = new AppUser()
            {
                UserName = "demouser@mail.com",
                Email = "demouser@mail.com",
                FirstName = "Demo",
                LastName = "User",
                EmailConfirmed = true,
            };

            await _userManager.CreateAsync(demoUser, "xxxxxx");
            await _dbContext.SaveChangesAsync();

            appUserId = _userManager.Users.FirstOrDefault(u => u.Email == "demouser@mail.com").Id;
        }

        private async Task SeedContactsAsync()
        {
            if (!_dbContext.Contacts.Any())
            {
                var contact = new List<Contact>()
                {
                    new Contact()
                    {
                        FirstName = "John",
                        LastName = "Dickens",
                        Address1 = "12 Main St.",
                        City = "Concord",
                        States  = ContactPro.Enums.States.NH,
                        ZipCode = 03101,
                        Email = "john@mail.com",
                        AppUserId = appUserId,
                    }
                };

                await _dbContext.Contacts.AddRangeAsync(contact);
                await _dbContext.SaveChanges();
            }
        }

        private async Task SeedCategoriesAsync()
        {
            if (!_dbContext.Categories.Any())
            {
                var category = new List<Category>()
                {
                    new Category()
                    {
                        Name = "_UnCategorized",
                        AppUserId = appUserId,
                    },
                };

                await _dbContext.Categories.AddRangeAsync(category);
                await _dbContext.SaveChanges();
            }
        }
    }
}

Solution

  • Please add the log to the method, and then print the appUserId in the console.

    My suggestion is to create a default value for the column or remove the not-null constraint from the column.

    using ContactPro.Data;
    using ContactPro.Models;
    using Microsoft.AspNetCore.Identity;
    
    namespace ContactPro.Helpers
    {
        public class DataSeeder
        {
            private readonly ILogger _logger;
            private readonly ApplicationDbContext _dbContext;
            private readonly UserManager<AppUser> _userManager;
    
            private static string appUserId;
    
            public DataSeeder(ApplicationDbContext dbContext, UserManager<AppUser> userManager,ILogger<DataSeeder> logger)
            {
                _dbContext = dbContext;
                _userManager = userManager;
                _logger = logger;
            }
    
            public async Task SeedDataAsync()
            {
                await SeedUsersAsync();
                await SeedContactsAsync();
                await SeedCategoriesAsync();
            }
    
            private async Task SeedUsersAsync()
            {
                if (_dbContext.Users.Any())
                {
                    return;
                }
    
                var demoUser = new AppUser()
                {
                    UserName = "demouser@mail.com",
                    Email = "demouser@mail.com",
                    FirstName = "Demo",
                    LastName = "User",
                    EmailConfirmed = true,
                };
    
                await _userManager.CreateAsync(demoUser, "xxxxxx");
                await _dbContext.SaveChangesAsync();
                _logger.LogInformation("****** at {DT}", 
            DateTime.UtcNow.ToLongTimeString());
                appUserId = _userManager.Users.FirstOrDefault(u => u.Email == "demouser@mail.com").Id;
                _logger.LogInformation("****** at {DT}", 
            DateTime.UtcNow.ToLongTimeString());
            }
    
            private async Task SeedContactsAsync()
            {
                _logger.LogInformation("****** at {DT}", 
            DateTime.UtcNow.ToLongTimeString());
    
                if (!_dbContext.Contacts.Any())
                {
                    var contact = new List<Contact>()
                    {
                        new Contact()
                        {
                            FirstName = "John",
                            LastName = "Dickens",
                            Address1 = "12 Main St.",
                            City = "Concord",
                            States  = ContactPro.Enums.States.NH,
                            ZipCode = 03101,
                            Email = "john@mail.com",
                            AppUserId = appUserId,
                        }
                    };
                    _logger.LogInformation("****** at {DT}", 
            DateTime.UtcNow.ToLongTimeString());
    
                    await _dbContext.Contacts.AddRangeAsync(contact);
                    await _dbContext.SaveChanges();
                }
            }
    
            private async Task SeedCategoriesAsync()
            {
                _logger.LogInformation("****** at {DT}", 
            DateTime.UtcNow.ToLongTimeString());
    
                if (!_dbContext.Categories.Any())
                {
                    var category = new List<Category>()
                    {
                        new Category()
                        {
                            Name = "_UnCategorized",
                            AppUserId = appUserId,
                        },
                    };
                    _logger.LogInformation("****** at {DT}", 
            DateTime.UtcNow.ToLongTimeString());
    
                    await _dbContext.Categories.AddRangeAsync(category);
                    await _dbContext.SaveChanges();
                }
            }
        }
    }