-
-
Save weedkiller/84e8db1479465c75fa9a3af95916c3b0 to your computer and use it in GitHub Desktop.
ASP.NET Identity Seed a database in a console application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNet.Identity.EntityFramework; | |
using Microsoft.AspNet.Identity; | |
using System; | |
using System.Data.Entity; | |
using System.Threading.Tasks; | |
namespace SeedDb | |
{ | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var db = new MyDbContext(); | |
db.Database.Initialize(true); | |
} | |
} | |
public class MyDbContext : IdentityDbContext<IdentityUser> | |
{ | |
public MyDbContext() | |
: base("DefaultConnection") | |
{ | |
} | |
static MyDbContext() | |
{ | |
Database.SetInitializer<MyDbContext>(new ApplicationDbInitializer()); | |
} | |
} | |
public class ApplicationDbInitializer : DropCreateDatabaseAlways<MyDbContext> | |
{ | |
protected override void Seed(MyDbContext context) | |
{ | |
var ttime = DateTime.Now; | |
for (int j = 0; j < 100; j++) | |
{ | |
var usermanager = new AppUserManager(new AppUserStore(new MyDbContext())); | |
var start = DateTime.Now; | |
for (int i = 0; i < 100; i++) | |
{ | |
var email = "user" + ((j * 100) + i) + "@constoso.com"; | |
var tempuser = new IdentityUser() { UserName = email, Email = email }; | |
usermanager.Create(tempuser, "ASP+Rocks4U"); | |
} | |
usermanager.SaveAll(); | |
usermanager.Dispose(); | |
} | |
Console.WriteLine("Time taken to complete iteration all: "+(DateTime.Now - ttime)); | |
base.Seed(context); | |
} | |
} | |
public class AppUserManager : UserManager<IdentityUser> | |
{ | |
public AppUserManager(AppUserStore store) | |
: base(store) | |
{ | |
} | |
public void SaveAll() | |
{ | |
var appstore = Store as AppUserStore; | |
appstore.SaveAll(); | |
} | |
} | |
public class AppUserStore : UserStore<IdentityUser> | |
{ | |
public AppUserStore(MyDbContext ctx) | |
: base(ctx) | |
{ | |
AutoSaveChanges = false; | |
} | |
public void SaveAll() | |
{ | |
Context.SaveChanges(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment