私はボランティアをしているユナイテッドウェイのために作成しているデータベースにシードする作業をしています。 (ボランティアと学習に興味がある場合はTapRoot +をチェックしてください)ドットネットコアエンティティフレームワークデータベースをシードするためのより良い方法は?
とにかく、私は今では1つのテーブルから1つのテーブルだけを操作するしかありません。
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()でサービスを作成しています。
とそれぞれの呼び出しは間違いなく、依存表にDBを作成し、それらのIDを参照する方法を知っておく必要があり.Configure(Seed Seeder)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Seed seeder)
{
seeder.SeedCounty().Wait();
seeder.SeedCity().Wait();
seeder.SeedLocation().Wait();
にメソッドを追加します。
Dictionary<string, int> County;
Dictionary<string, int> City;
Dictionary<string, int> Address;
Dictionary<string, int> ServiceType;
Dictionary<string, int> Organization;
Dictionary<string, int> Contact;`
および内でそれらを移入:
私は多対多の関係でリンクテーブルをシードする必要がある場合にも好奇心...