Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seed method not called with EntityFramework CodeFirst

I've been struggling on and off with this problem since 4.1 (now I'm on 4.3). It seems to me that to get the seed method called, all I should have to do is the following:

1) Create an empty data catalog on sqlserver 2) Execute the code below:

Database.SetInitializer(new DropCreateDatabaseAlways<SiteDB>());

I have my SiteDB defined as follows:

public class SiteDBInitializer : 
    DropCreateDatabaseAlways<SiteDB>
{
    protected override void Seed(SiteDB db)
    {
           ... (break point set here that never gets hit)

I feel like I must be missing something very simple because this creates my tables, but does never calls the seed method.

To Make this more clear, here is a full example that includes all the code. When I run it, seed never gets called:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace ConApp
{
internal class Program
{
    private static void Main(string[] args)
    {
        Database.SetInitializer(new SiteDBInitializer());
        using (var db = new SiteDB())
        {
            var x = db.Customers;
        }
    }
}

public class SiteDB : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

public class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public string LastName { get; set; }
}

public class SiteDBInitializer :
    DropCreateDatabaseAlways<SiteDB>
{
    protected override void Seed(SiteDB db)
    {
        db.Customers.Add(new Customer() {LastName = "Kellner"});
        db.Customers.Add(new Customer() {LastName = "Jones"});
        db.Customers.Add(new Customer() {LastName = "Smith"});
        db.SaveChanges();
    }
}

}
like image 431
Peter Kellner Avatar asked Feb 17 '12 02:02

Peter Kellner


People also ask

What is data seeding in EF core?

Data seeding is the process of populating a database with an initial set of data. There are several ways this can be accomplished in EF Core: Model seed data. Manual migration customization. Custom initialization logic.


1 Answers

You need call Database.SetInitializer(new SiteDBInitializer()); instead.

like image 69
J.W. Avatar answered Oct 22 '22 18:10

J.W.