【问题标题】:Better way to Seed a Dot Net Core Entity Framework Database?播种点网核心实体框架数据库的更好方法?
【发布时间】: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


【解决方案1】:

所以关键是创建明确的字典:

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
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2018-05-19
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多