Search code examples
entity-frameworkentity-framework-4ef-code-firstcode-first

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();
    }
}

}

Solution

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