В таблице «Категории» данные отображаются нормально. Но я не могу получить данные в таблицах: «Подкатегории» и «Товары». Значения в столбцах == null. Внешние ключи между таблицами появляются при просмотре дизайнером. Раньше таких проблем не было, но вдруг возникла проблема с использованием асинхронности.

  1. Image1 2) Изображение2 Logger1: Logger Logger2: Logger
public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        CreateIfDbNotExists(host);
        host.Run();
    }

    public static void CreateIfDbNotExists(IHost host)
    {
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var loggerFactory = services.GetRequiredService<ILoggerFactory>();
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                ApplicationDbContextSeed.SeedAsync(context, loggerFactory).Wait();
            }
            catch(Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

РЕДАКТИРОВАТЬ:
Модели сущностей -



public class Category
{
    public int CategoryID { get; set; }

    [Required]
    [StringLength(30)]
    [Display(Name = "Name")]
    public string CategoryName { get; set; }

    public string ImagePath { get; set; }

    [Display(Name = "Category Description")]
    public string Description { get; set; }

    public virtual ICollection<SubCategory> SubCategories { get; set; }
}

public class SubCategory
{
    public int SubCategoryID { get; set; }

    [Required]
    [StringLength(30)]
    [Display(Name = "Name")]
    public string SubCategoryName { get; set; }

    [Display(Name = "SubCategory Description")]
    public string Description { get; set; }

    public int? CategoryID { get; set; }

    public virtual Category Category { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

DbContext -

public class ApplicationDbContext: DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

    public DbSet<Category> Categories { get; set; }

    public DbSet<SubCategory> SubCategories { get; set; }

    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Category>().ToTable("Category");
        
        modelBuilder.Entity<SubCategory>().ToTable("SubCategory");
        
        modelBuilder.Entity<Product>().ToTable("Product");
    }
}

Заполнение данных -

public static class ApplicationDbContextSeed
{
    public static async Task SeedAsync(ApplicationDbContext _context, ILoggerFactory loggerFactory)
    {
        try
        {
            _context.Database.EnsureCreated();
            await SeedCategoriesAsync(_context);
            await SeedSubCategories(_context);
            await SeedProduct(_context);
        }
        catch(Exception ex)
        {
            var log = loggerFactory.CreateLogger<ApplicationDbContext>();
            log.LogError(ex.Message);
        }
    }
    
    private static async Task SeedCategoriesAsync(ApplicationDbContext _context)
    {
        if (_context.Categories.Any()) return;
        var categories = new List<Category>()
        {
            new Category
            {
                Description = "Some category",
                CategoryName = "Electronics"
            },
            new Category
            {
                Description = "Some category",
                CategoryName = "Computers"
            },
            new Category
            {
                Description = "Some category",
                CategoryName = "Music"
            },
            new Category
            {
                Description = "Some category",
                CategoryName = "Software"
            },
            new Category
            {
                Description = "Some category",
                CategoryName = "Arts"
            },
            new Category
            {
                Description = "Some category",
                CategoryName = "Games"
            },
        };
        _context.Categories.AddRange(categories);
        await _context.SaveChangesAsync();
    }

    private static async Task SeedSubCategories(ApplicationDbContext _context)
    {
        if (_context.SubCategories.Any()) return;
        var subCategories = new List<SubCategory>
        {
            new SubCategory
            {
                CategoryID =  _context.Categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                SubCategoryName = "Camera",
                Description = "Some"
            },
            new SubCategory
            {
                CategoryID =  _context.Categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                SubCategoryName = "Phones",
                Description = "Some"
            },
            new SubCategory
            {
                CategoryID =  _context.Categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                SubCategoryName = "Headphones",
                Description = "Some"
            },
            new SubCategory
            {
                CategoryID =  _context.Categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                SubCategoryName = "Video Game Consoles && Accessories",
                Description = "Some"
            },
        };
        _context.SubCategories.AddRange(subCategories);
        await _context.SaveChangesAsync();
    }

    private static async Task SeedProduct(ApplicationDbContext _context)
    {
        if (_context.Products.Any()) return;
        var products = new List<Product>
        {
            new Product
            {
                ProductName = "iPhone 12 Pro Max",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Phones").SubCategoryID,
                UnitPrice = 1695.66,
                ImagePath = "iphone12.webp"
            },
            new Product
            {
                ProductName = "iPhone 11 Pro Max",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Phones").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "Xiaomi 9 Pro",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Phones").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "Canon PowerShot SX540 Digital Camera",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "Panasonic LUMIX FZ300",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "Panasonic LUMIX FZ300",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "4K Digital Camera 48MP Camera",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "TOZO T10 Bluetooth 5.0", 
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Headphones").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "TOZO T6 True Wireless",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Headphones").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "Razer Kraken Tournament Edition",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Headphones").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "Sony PlayStation 4 Pro (1TB) Console with Red Dead Redemption 2 Bundle",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Video Game Consoles && Accessories").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
            new Product
            {
                ProductName = "PlayStation 4 Console - 1TB Slim Edition",
                SubCategoryID = _context.SubCategories.FirstOrDefault(s => s.SubCategoryName == "Video Game Consoles && Accessories").SubCategoryID,
                UnitPrice = 1395.66,
                ImagePath = "iphone12.webp",
                Description = "Some phone"
            },
        };

        _context.Products.AddRange(products);
        await _context.SaveChangesAsync();
    }
}
public class Product
{
    public int ProductID { get; set; }

    [Required]
    [StringLength(100)] 
    [Display(Name = "Name")]
    public string ProductName { get; set; }

    public string Description { get; set; }

    public string ImagePath { get; set; }

    [Display(Name = "Price")]
    public double UnitPrice { get; set; }

    public int? SubCategoryID { get; set; }

    public virtual SubCategory SubCategory { get; set; }
}
0
Evgeny20 22 Фев 2021 в 01:10

1 ответ

Лучший ответ

Я обнаружил, что SubCategoryName слишком короткое для «Video Game Consoles && Accessories». Это дает исключение. Теперь это varchar (30). Должно быть как минимум varchar (50). Все таблицы были успешно заполнены после того, как я сократил некоторые значения названия подкатегории и названия продукта.

Я рекомендую вам исправить классы SubCategory и Product, заменив [StringLength (30)] на [StringLength (96)] или даже больше.

....
    [StringLength(96)]
    [Display(Name = "Name")]
    public string SubCategoryName { get; set; }

  [StringLength(96)]
    [Display(Name = "Name")]
    public string ProductName { get; set; }
.....



1
Sergey 22 Фев 2021 в 02:44