As the user @trailmax suggested I was not choosing the best place to insert default users for Identity, since I was inserting the users each time the constructor of the context was called.
After analysis of course that's not a good option, because every time I access my DbSets I use the context constructor, triggering additional sql queries to Roles and Users DbSets, without need (because I only need that query on the startup to insert the users if they don't exist).
So.. since my web-hosting plan don't allow any Update Migrations neither Seed Methods to be runnable from Package Manager Console (because it always reference the 'master' database which I don't have permissions), I figured out this solution:
1) I create all my tables running a sql script on my remote mssql database (to get the generated SQL Script from my contexts and models, I type the following command in Package Manager Console:
Update-Database -Script -SourceMigration:0
2) Then I need to set Database Initializer to null, so EF doesn't try to drop/create a Database and finnaly I just invoke a method on my Context Class from my Global.asax in the method Application_Start:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<MyContext>(null);
new MyContext().CreateDefaultUsers();
}
3) And here is my method, that is only called on Application Startup (I am almost sure about it, at least I hope so, I wanna save CPU Clocks!)
public class MyContext : IdentityDbContext<IdentityUser>
{
public MyContext() : base("MyContext")
{
}
internal void CreateDefaultUsers()
{
if (!Roles.Any(r => r.Name == "admin"))
{
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this));
RoleManager.Create(new IdentityRole("admin"));
}
if (!Users.Any(u => u.UserName == "myadmin"))
{
var store = new UserStore<IdentityUser>(this);
var manager = new UserManager<IdentityUser>(store);
var user = new IdentityUser { UserName = "myadmin" };
manager.Create(user, "mysupersafepwlulz");
manager.AddToRole(user.Id, "admin");
}
}
//More stuff not relevang for the question...
}
I hope this helps someone out there, and thank you @trailmax !
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…