Seeding DB made by Code First EF Core DB

c# entity-framework-core


I am wondering what is the best way to generate required data right after EF Core has made the database.

I see that people make classes in the C# code to do it but how about if you got alot of data? For me I got to import all States from the US in my system.

I would think it would be better to run some sort of sql script to do this, but I guess some check would be needed for duplicates.


Say I want to use these scripts that I found in my database. So when my database is auto generated when my project runs for the first time they get populated.

6/17/2018 5:20:52 PM

Accepted Answer

If you are using EF Core 2.1 they have actually added a new feature that is very nice.

EF Core 2.1 Release Announcement

In your OnModelCreating method of your DbContext you now have an HasData extension method on the Entity method.

Here are two examples:

modelBuilder.Entity<Blog>().HasData(new Blog {BlogId = 1, Url = ""});

    new {BlogId = 1, PostId = 1, Title = "First post", Content = "Test 1"},
    new {BlogId = 1, PostId = 2, Title = "Second post", Content = "Test 2"});
6/15/2018 9:47:03 PM

Popular Answer

To generate a lot of data, you can use a lib like Bogus which is "is fundamentally a C# port of faker.js and inspired by FluentValidation's syntax sugar". We use it in our project and it fits perfect. You can generate real name, real countries, real phone numbers etc. An example from GitHub:

var testUsers = new Faker<User>()
    .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))
    .RuleFor(u => u.Gender, f => f.PickRandom<Gender>())
    .RuleFor(u => u.FirstName, (f, u) => f.Name.FirstName(u.Gender))
    .RuleFor(u => u.LastName, (f, u) => f.Name.LastName(u.Gender))
    .RuleFor(u => u.Avatar, f => f.Internet.Avatar())
    .RuleFor(u => u.UserName, (f, u) => f.Internet.UserName(u.FirstName, u.LastName))
    .RuleFor(u => u.Email, (f, u) => f.Internet.Email(u.FirstName, u.LastName))
    .RuleFor(u => u.SomethingUnique, f => $"Value {f.UniqueIndex}")
    .RuleFor(u => u.CartId, f => Guid.NewGuid())
    .RuleFor(u => u.FullName, (f, u) => u.FirstName + " " + u.LastName)
    .RuleFor(u => u.Orders, f => testOrders.Generate(3).ToList())
    .FinishWith((f, u) =>
            Console.WriteLine("User Created! Id={0}", u.Id);

var user = testUsers.Generate(10000); // Generated 10000 users that match rules

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow