【发布时间】:2018-01-15 10:03:36
【问题描述】:
我正在努力为我正在志愿服务的 United Way 创建一个数据库。 (如果您对志愿服务和应用一些学习感兴趣,请查看 TapRoot+)
无论如何,我现在只播种一对多的字段,但我已经让它一次工作一张桌子。
public class Seed
{
private CharEmContext _context;
public Seed(CharEmContext context)
{
_context = context;
}
public async Task SeedCounty()
{
if (!_context.Counties.Any())
{
_context.AddRange(_counties);
await _context.SaveChangesAsync();
}
}...`
和
static List<County> _counties = new List<County>
{
new County { Name = "Emmet"},
new County { Name = "Charlevoix"},
new County { Name = "Antrim"},
new County { Name = "Cheboygan"},
new County { Name = "Otsego"},
new County { Name = "None"}
};
但是当我尝试引用创建后分配的 Id 时遇到了麻烦。
这都不是:
static List<City> _cities = new List<City>
{
new City { Name = "Alanson", CountyId = _context.Counties.Where(x=>x.Name =="Emmet").Select(x => x.Id).FirstOrDefault()}, ... }
也不是这样:
static List<City> _cities = new List<City>
{
new City { Name = "Alanson", CountyId = _counties.Where(x=>x.Name =="Emmet").Select(x => x.Id).FirstOrDefault()},
有效。
作为参考,我正在我的startup.cs.ConfigureServices 中创建一个服务
services.AddTransient();
并在.Configure(Seed Seeder)中调用每个add方法
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Seed seeder)
{
seeder.SeedCounty().Wait();
seeder.SeedCity().Wait();
seeder.SeedLocation().Wait();
绝对需要知道如何引用数据库在依赖表上创建的那些 ID。
我也很好奇我是否需要在多对多关系中播种链接表......
【问题讨论】:
标签: c# sql-server .net-core entity-framework-core seeding