2017-08-08 93 views
0

我正在努力創建一個數據庫,我正在爲志願服務的聯合之路創建數據庫。 (如果你對志願服務感興趣並申請一些學習,請查看TapRoot +)種子Dot Net核心實體框架數據庫的更好方法?

無論如何,我現在只播種一到多個領域,但我一次只能在一張桌子上播種。

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)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Seed seeder) 
{ 
    seeder.SeedCounty().Wait(); 
    seeder.SeedCity().Wait(); 
    seeder.SeedLocation().Wait(); 

添加方法絕對需要知道如何引用在從屬表的DB創建這些ID。

如果我需要種子在許多一對多關係的鏈接表也很好奇......

回答

0

所以關鍵是要建立明確的字典:

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 
    } 
相關問題