Skip to content

Instantly share code, notes, and snippets.

@rustd
Last active September 24, 2020 07:25
Show Gist options
  • Save rustd/10788421 to your computer and use it in GitHub Desktop.
Save rustd/10788421 to your computer and use it in GitHub Desktop.
ASP.NET Identity Seed a database in a console application
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