How to Seed Your Database With EF Core

后端存储 DZone (源链)

How to Seed Your Database With EF Core

DZone’s Guide to

How to Seed Your Database With EF Core

Learn how to automate the data migration of your web application programmatically using Entity Framework Core and C# functions.

Simone Chiaretta

Jan. 13, 18 ·
Web Dev Zone

Free Resource

Join the DZone community and get the full member experience.

Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.

Yesterday, I showed how to do EF Core DB migrations using either the Package Manager Console or the .NET CLI. But you can also do these code migrations automatically, triggering them via code.

After following the steps shown yesterday , you have all your migrations setup, and you can apply the DB changes using the dotnet CLI. But there is a lesser-known feature, that is still experimental and not ironed out completely, that makes it possible to run migrations from code, and even seed the DB with initial data.

Apply Migrations With Code

To just apply migrations you need to call the db.Database.Migrate() method, where db is the EF Context.

Typically, the following is the code needed to run the migration in code:

public static void Initialize(IServiceProvider service)
{
    using (var serviceScope = service.CreateScope())
    {
        var scopeServiceProvider = serviceScope.ServiceProvider;
        var db = scopeServiceProvider.GetService();
        db.Database.Migrate();
    }
}

This method can be called in the Configure method in the Startup class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  ...
  Initialize(app.ApplicationServices);
}

Seeding the DB With Data

As part of the database initialization, you can also add some initial test data to the database. Unfortunately, it is not as automated as in Entity Framework 6, but can be coded manually.

For example, to add a new entry in the Race table, the code is as follows:

private static async Task InsertTestData(TriathlonRaceTrackingContext context)
{
    if(context.Races.Any())
        return;
    var race = new Race { Name="Ironman World Championship 2017",Location="Kona, Hawaii",Date=new DateTime(2017,10,14,7,0,0) };
    context.Add(race);
    await context.SaveChangesAsync();
}

The advantage of having to code it yourself is that you can decide if/when/how to seed the database. In this code, I just do it if the Race table is empty. But I could have decided to always wipe it clean, or anything else.

To include data seeding into the Initialize method, a few changes have to be made as the data seeding is an async method. So the Initialize becomes an InitializeAsync :

public static async Task InitializeAsync(IServiceProvider service)
{
    using (var serviceScope = service.CreateScope())
    {
        var scopeServiceProvider = serviceScope.ServiceProvider;
        var db = scopeServiceProvider.GetService();
        db.Database.Migrate();
        await InsertTestData(db);
    }
}

Also, the call from the Configure method must be slightly changed to InitializeAsync(app.ApplicationServices).Wait(); .

Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

DOWNLOAD

Topics:

web dev , data migration , entity framework , web application data

Published at DZone with permission of Simone Chiaretta , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

DZone责编内容来自:DZone (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » How to Seed Your Database With EF Core

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录