【发布时间】:2021-02-21 22:10:19
【问题描述】:
在“类别”表中,数据正常显示。但我无法在表格中获取数据:“子类别”和“产品”。列中的值为 == null。设计人员查看时会出现表之间的外键。以前是没有这样的问题的,突然使用异步就出现了问题。
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<SubCategories>() { new SubCategory() { Name = "somename", Products = new List<Product>() { new Product(){} } } } } -
好吧,格式出错了希望你明白这个想法????
-
您是否看到记录了任何异常消息?
标签: c# asp.net-mvc entity-framework asp.net-core entity-framework-core