I'm trying to rename the default table names generated by ASP.net Identity 2.0. I read all the articles, the questions and the answers on stackoverflow but im still getting the same error.
I renamed the tables to Roles, UserClaims, Logins, UserRoles and Users. I also changed the application dbcontext to the following
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("Users", "dbo");
modelBuilder.Entity<IdentityRole>().ToTable("Roles", "dbo");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles", "dbo");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims", "dbo");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins", "dbo");
}
}
But i keep getting the Invalid object name 'dbo.AspNetUsers'. error, and I have no idea why its still trying to locate AspNetUsers in the first place instead of just Users although i made the changes above. Totally desperate by now.
The database as well, same columns with the new table names:
And the SQL database project:
You need to update database. Enable-Migrations and Update-Database, explained in details here. The point of EF code first approach is to write our model classes and configurations and each time we change something we use EF migrations to update the database schema.
Database first approach with asp.net-identity-entityframework are explained here and here, not so straightforward
Write the following code in IdentityModels.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DBConnectionString", throwIfV1Schema: false)
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<ApplicationUser>().ToTable("Users");
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Write the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer<ApplicationDbContext>(null);
Related
I'm using EntityFrameworkCore Code First to create my SQL migration scripts.
After every change in my model, I run Add-Migration changeInModel and a corresponding XXXXXXXX_changeInModel.cs file is being generated in my Migrations folder.
If I don't make any change in my models AND I run Add-Migration noChangeInModel , I was assuming (out of nowhere) no generation of XXXXXX_noChangeInModel.cs
However, EF Core is creating a XXXXXX_noChangeInModel.cs with an empty Up and Down methods.
Is that supposed to be the expected behavior? Or should EF Core just skip the generation of an empty .cs file? I can't find any reference to this in the documentation.
I have taken my main project and stripped out all the code up to the bare minimum to find out whether is the behavior or some sort of bug in my configuration.
Below the minimum core to reproduce generating empty Up/Down methods with no change in models, with the following Nuget packages:
Microsoft.EntityFrameworkCore 2.2.6
Microsoft.EntityFrameworkCore.SqlServer 2.2.6
Microsoft.EntityFrameworkCore.Tools 2.2.6
Microsoft.NETCore.App 2.2.0
namespace TestingEFCore
{
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var connectionString = "Server=localhost;Database=TEST2;Integrated Security=SSPI;";
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connectionString);
return new BloggingContext(optionsBuilder.Options);
}
}
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
}
I would expect no XXXXXX_noChangeInModel.cs being generated, but a I get migrations with empty Up/Down methods. I can't find the documentation to describe this use case.
I think it is expected behavior. Consider the case when you have no changes in model but you need to add some data in your db like this
public partial class your_migration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"your sql");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"sql to clean up data");
}
}
Without an empty migration for no changes in model generated it would be impossible to obtain such migration.
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.
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.
I am working with ASP.NET identity. I renamed the default tables using the following code.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("Users");
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
}
}
}
But when I run my app, AspnetUsers is still created but with a single column named 'Id'. This table is being populated along with the new "Users" table. Why? And how do I stop this behavior.
I see the same question asked here, but without a good response: Identity 2.0 Code First Table Renaming
I hope I am not violating StackOverflow's guidelines in reasking this question/// if so apologies in advance!
Stumbled across this post when looking for a quick solution - now I've dug a bit through the code and found the answer; maybe it helps someone.
I suppose you have overwritten the default IdentityUser class, right?
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
...
In that case, you'll have to exclude the default IdentityUser from the ModelBuilder:
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<IdentityUser>().ToTable("Users", "dbo"); // we have overwritten IdentityUser, so no more need for the empty AspNetUsers table
modelBuilder.Entity<ApplicationUser>().ToTable("Users", "dbo"); // Use ApplicationUser instead
modelBuilder.Entity<IdentityRole>().ToTable("Roles", "dbo");
I have a new MVC5 project with ASP.NET Identity 2.0 and EF 6.1.1.
I added my own ApplicationUser (based on built-in IdentityUser). This is how my DbContext is created.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
When the database is created I have tables like AspNetUsers, AspNetUserRoles, AspNetUserClaims, and AspNetUserLogins. Then I added OnModelCreating() with just the most basic statements.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
As soon as I add OnModelCreating(), the identity tables are automatically renamed to ApplicationUsers, IdentityUserRoles, IdentityUserClaims, and IdentityUserLogins. That's fine with me (and I know how to rename them).
But what I don't like: All of a sudden, IdentityUserRoles, IdentityUserClaims, and IdentityUserLogins have an extra field called "ApplicationUser_Id". The original "AspNetXXX" tables didn't have such a field.
Why is that? And is there anything I can do in order to avoid this?
You need to call base.OnModelCreating. There are a number of additional things OnModelCreating does in IdentityDbContext that you may be missing without calling it - the default names of the tables being one of them.
Its best to call it first, then apply your own changes afterwards.
As mentioned by Matt Lassam-Jones
worked for me also and Thank You.
public class NebulaContext : IdentityDbContext<ApplicationUser>
{
public NebulaContext()
: base("Name=MyEntity", throwIfV1Schema: false)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //Optional
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();//Optional
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //Optional
base.OnModelCreating(modelBuilder);
}
}
I have added
public IEnumerable<Comment> Comments { get; set; }
to a Model in an ASP.net MVC project. I ran the following to generate a migration in the package console
PM> Add-Migration AddCommentsToDevice
and the resulting migration did not pick up the change to the model
public partial class AddCommentsToDevice : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Any tips on the syntax of the migrations or what causes detections?
You've added to little. You need to configure the relationship properly - the best with fluent api. Use this for navigation property:
public virtual ICollection<Comment> Comments { get; set; }
Important - always use ICollection, not IEnumerable for Navigation properties and make them virtual - thanks to this ef will be able to track changes.
Then in your DbContext you add following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model>().HasKey(x => x.Id);
modelBuilder.Entity<Model>().HasMany(x => x.Comments);
base.OnModelCreating(modelBuilder);
}
I assumed that class related to Comments is named Model.