Reputation: 1423
I'm working on an Asp.Net Mvc application then i want to seed my database using custom Database initializer class that I created.
so here is my DbContext
:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public ApplicationDbContext()
: base("defaultConnection", throwIfV1Schema: false) {
}
static ApplicationDbContext() {
Database.SetInitializer(new ApplicationDbInitializer());
}
and here is my ApplicationDbInitializer
class :
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> {
protected override void Seed(ApplicationDbContext context) {
InitializeIdentityForEF(context);
base.Seed(context);
}
public static void InitializeIdentityForEF(ApplicationDbContext db) {
// Create Role Admin if it does not exist
// Add user admin to Role Admin if not already added
// And some more initializing stuff
}
}
Note: I'm using Migrations
too.
so when i try to update and seed my database using command Update-Database
(even if I delete database manually) , the database is being created but it does not seed it.
if I am doing anything wrong or it has other ways I'll be thankful to get your assistance.
Upvotes: 0
Views: 452
Reputation: 7547
This sounds like the same issue as in this question.
So, the seed code will only run when you create an instance of your ApplicationDbContext
.
Add some code like this to your application startup:
var ctx = new ApplicationDbContext();
ctx.Database.Initialize(true);
Then your database will be seeded the next time your app starts.
Alternatively, if you wanted to use the Update-Database
command to seed your database, that uses a different Seed
method. You can see an example here.
Upvotes: 1