【问题标题】:Data does not appear in linked tables (SubCategory and Products)数据未出现在链接表中(子类别和产品)
【发布时间】:2021-02-21 22:10:19
【问题描述】:

在“类别”表中,数据正常显示。但我无法在表格中获取数据:“子类别”和“产品”。列中的值为 == null。设计人员查看时会出现表之间的外键。以前是没有这样的问题的,突然使用异步就出现了问题。

  1. Image1 2) Image2 记录器1:Logger 记录器2: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; }
}

【问题讨论】:

  • 尝试将ApplicationDbContextSeed.SeedAsync(context, loggerFactory).Wait();更改为await ApplicationDbContextSeed.SeedAsync(context, loggerFactory)
  • 首先通过应用“await”进行了尝试。没有帮助 =((
  • 为什么不将整个实体添加为new Category() { Name = "some category" SubCategories = new List&lt;SubCategories&gt;() { new SubCategory() { Name = "somename", Products = new List&lt;Product&gt;() { new Product(){} } } } }
  • 好吧,格式出错了希望你明白这个想法????
  • 您是否看到记录了任何异常消息?

标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core


【解决方案1】:

我发现 SubCategoryName 对于“Video Game Consoles && Accessories”来说太短了。这给出了一个例外。现在是 varchar(30)。至少应该是 varchar(50)。在我缩短了一些子类别名称和产品名称值后,所有表都已成功播种。

我建议您通过将 [StringLength(30)] 替换为 [StringLength(96)] 甚至更大来修复 SubCategory 和 Product 类。

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

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



【讨论】:

  • @Evgeny20 谢谢你太多了。只要你接受答案就足够了。
猜你喜欢
  • 2017-06-04
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
相关资源
最近更新 更多