I know this question might be duplicated, but I haven’t found any solution for my problem yet.
I have:
protected void Application_Start()
{
Database.SetInitializer(new DatabaseSeeder());
DatabaseContext c = new DatabaseContext();
c.Database.Initialize(true);
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
my database seeder is:
public class DatabaseSeeder : DropCreateDatabaseAlways<DatabaseContextBase>
{
protected override void Seed(DatabaseContextBase context)
{
base.Seed(context);
var roles = new[] {"Admin", "User"};
foreach (var role in roles)
{
context.Roles.Add(new UserRole {FullName = role});
}
context.SaveChanges();
}
}
and my context is:
public abstract class DatabaseContextBase : DbContext
{
public DbSet<UserRole> Roles { get; set; }
public DbSet<UserAndPermissionInGroup> UserAndPermissions { get; set; }
public DbSet<GeneralUser> Users { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Forum> Forums { get; set; }
public DatabaseContextBase() :base("ForumDb")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Comment>()
.HasRequired(e => e.Owner)
.WithMany(t => t.Comments)
.HasForeignKey(e => e.OwnerId)
.WillCascadeOnDelete(false);
}
}
And finally:
public class DatabaseContext : DatabaseContextBase
{
}
The problem is that, even with this initializer, I get the following error:
The model backing the ‘DatabaseContext’ context has changed since the
database was created. Consider using Code First Migrations to update
the database
I am using EF 5 code first in an ASP.NET MVC 3 project. Any suggestions?
It looks like Database.SetInitializer does not work for derived types. I changed the initializer from
to
and now the code:
works pretty well. Thanks for all answers.