我正在努力為我正在為志願服務的聯合之路創建一個數據庫。 (如果您對志願服務和應用一些學習感興趣,請查看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時嘗試引用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();
當然需要知道如何引用DB在依賴表上創建的ID。
同樣好奇我是否需要在多對多關係中播種鏈接表...
所以關鍵是要創建明確的詞典:
Dictionary<string, int> County;
Dictionary<string, int> City;
Dictionary<string, int> Address;
Dictionary<string, int> ServiceType;
Dictionary<string, int> Organization;
Dictionary<string, int> Contact;`
並在種子動作中填充它們:
public async Task SeedCounty()
{
if (!_context.Counties.Any())
{
_context.AddRange(_counties);
await _context.SaveChangesAsync();
}
County = _context.Counties.ToDictionary(p => p.Name, p => p.Id);
}
然後,要創建引用現在播種的ID的後續列表,將單獨調用以創建要播種的每個從屬列表:
public async Task SeedCity()
{
CreateCities(); // Create Dependent List
if (!_context.Cities.Any())
{
_context.AddRange(_cities); //Seed List
await _context.SaveChangesAsync();
}
City = _context.Cities.ToDictionary(p => p.Name, p => p.Id); //Create Dictionary with New Ids
}