ASP.NET Core 6 MVC数据填充器未填充类别。

huangapple go评论60阅读模式
英文:

ASP.NET Core 6 MVC data seeder not populating categories

问题

在下面的代码中,AppUserContact 被创建了,但Category没有被创建。终端中的错误是...

> 列"Categories"的列"AppUserId"中的空值违反了非空约束

这是一个具有一对多关系的Postgresql数据库,包括 AppUserContactAppUserCategory。我可以在应用程序中成功创建一个类别,并且显示NameAppUser字段都正确填充了,但出于某种原因Seeder没有执行相同的操作。

这很奇怪,因为联系人记录的AppUserId正确填充了。我不明白为什么它不会为Category记录执行相同的操作。有什么想法吗?

以下是代码:

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.SaveChangesAsync();
            }
        }

        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.SaveChangesAsync();
            }
        }
    }
}
英文:

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();
}
}
}
}

答案1

得分: 1

在方法中添加日志1,然后在控制台打印appUserId。

英文:

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();
}
}
}
}

huangapple
  • 本文由 发表于 2023年5月15日 05:26:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定