저는 제가 자원하고있는 유나이티드 웨이 (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가 생성되면 할당 된 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를 참조하는 f}을 확실히 알아야합니다.
또한 다 대다 관계에서 연결 테이블을 시드해야하는지 궁금해 ...
따라서 핵심은 명시적인 사전을 만드는 것이 었습니다.
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
}