代码之家  ›  专栏  ›  技术社区  ›  Craig W.

使用ef core 2.2播种变量数据

  •  1
  • Craig W.  · 技术社区  · 7 年前

    在我所看到的所有关于使用ef核心播种数据的示例和文章中,所有数据都是硬编码的。我需要在数据的一部分是可变的地方输入一些数据。我的模型是:

    public class Customer
    {
        [Key]
        public Guid Id { get; set; }
    
        public string ApiKey { get; set; }
    }
    

    具体来说,我想要 ApiKey 每次种子操作运行时包含不同的值。这样,我就可以为每个环境(开发、质量保证、生产)获得不同的价值。

    我创建了一个生成唯一值的方法,并将以下内容添加到 OnModelCreating 方法。

    modelBuilder.Entity<Customer>().HasData(new Customer
    {
        Id = Guid.NewGuid(),
        ApiKey = GenerateApiKey()
    });
    

    你可能已经猜到,问题在于 GenerateApiKey 在创建迁移时发生,因此 通用APIKEY 有效地硬编码到 InsertData 打电话。

    migrationBuilder.InsertData(
        table: "Customers",
        columns: new[] { "Id", "ApiKey" },
        values: new object[] 
        { 
            new Guid("bcde0c82-ad26-47fb-bd5f-1ad552d2b8f0"),
            "56+hhUTjPwz0FM9uwYg19M5rfq6aUgmNde15Frn6TFY=" 
        });
    

    在EF6.x中,我用 Seed 我的方法 DbMigrationsConfiguration 子类。

    我意识到我可以修改迁移,但是我们正处于开发阶段,在更改期间我们将删除并重新创建数据库,这将要求每个开发人员在重新生成初始迁移时都要记住这一点。我宁愿做得更简单一点。

    1 回复  |  直到 7 年前
        1
  •  1
  •   PmanAce    7 年前

    一旦主机准备好了,您就可以运行seed方法(这是我在2.1中所做的):

    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Seed().Run();
    }
    
    ...
    
    public static class WebHostExtensions
    {
        public static IWebHost Seed(this IWebHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService<ILoggerFactory>();
                var context = services.GetRequiredService<MsbContext>();
    
                // do whatever you need here with your data before migrations
                ...
                context.Database.Migrate();
    
                // do whatever you need here with your data after migrations
                ...
            }
        }
    }
    
    推荐文章