2

This Is my Context class

 public class TestContext : IdentityDbContext<ApplicationUser>
{
    public TestContext()
        : base("DefaultConnection")
    {

    }
    public DbSet<UserTestModel> UserTestModel { get; set; }
    public DbSet<SubscriptionTestModel> SubscriptionTestModel { get; set; }
    public DbSet<QATestModel> QATestModel { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new TestContextInitializer());
    }
}

and this is initializer class

public class TestContextInitializer : DropCreateDatabaseAlways<TestContext>
{
    protected override void Seed(TestContext context)
    {
        var user = new List<UserTestModel>{
            new UserTestModel{
                Id="1",
                UserName="Admin",
                Password="Admin123"
            },
            new UserTestModel{
                Id="2",
                UserName="User",
                Password="User123"
            }
        };
        user.ForEach(d=>context.UserTestModel.Add(d));


    }
}

In this code DropCreateDatabaseAlways not dropping database. The database does not contain any foreign key or relationship. How to resolve this?

Twix
  • 392
  • 1
  • 12
  • 38

1 Answers1

0

In your Global.asax file add the following:

protected void Application_Start(object sender, EventArgs e)
{
    Database.SetInitializer<TestContext>(new TestContextInitializer());
}

It worked for me. This is a great video how to populate database with seed data:

https://www.youtube.com/watch?v=XED_WgDmK4c

EDIT

If you call it from the test method then this should do the trick:

Database.SetInitializer<TestContext>(new TestContextInitializer());
_dataCntx = new TestContext();
_dataCntx.Database.Initialize(true);
Community
  • 1
  • 1
Dawid O
  • 6,091
  • 7
  • 28
  • 36
  • I do not have Global.asax file as I am using this context class in my test project. – Twix Sep 09 '14 at 13:02