There is already an object named 'AspNetUsers' in the database - asp.net-mvc

I have searched all over the internet, stack overflow but i am feeling lost in the mystery of Entity framework Migration.
I have existing database. I have added three new tables which have some relation with AspNetUsers table.
I have tried two ways to add these tables to database using pmc.
first comment out all new tables in dbcontext and then use following command.
Add-migration initial -ignorechanges
then uncomment the tables from dbcontext and run update-database command. result no new table added.
then i remove all the entries in migration history table and remove migration folder and start from scratch.
enable-migrations -EnableAutomaticMigrations
Add-migration bcvn
update-database -verbose
now, when i run update database, it says There is already an object named 'AspNetUsers' in the database.Found this article to be helpfull but in my case there are no changes going on AspNetUsers table in up method so i can follow this article http://blog.rajsoftware.com/2014/07/12/entity-framework-code-first-automatic-migration-existing-tables/ Please someone save me.May be i will receive many downvote .but i dont care i want solution.

Got it working. The Trick was to comment out all the code related to new table especially the relationship related code which i was not doing before to ApplicationUser class then
Add-migration initial -ignorechanges
then uncomment all the code and then
update-database -verbose
The only thing which i was not doing before was to comment out the relationship like this--
// public virtual Notification Notifications { get; set; }
and in notification table
// public virtual ApplicationUser ApplicationUser { get; set; }
May be helpful for someone too.

Related

Migration with Entity Framework 6 code first

I have an ASP.NET MVC project using EF code first and migrations.
I am trying to add a new property to a class. For that I create the migration code in order to add the specific column in the table related to that class.
My migration code is the following:
public partial class Add_DataRequisicao_to_BiblRequisicao : DbMigration
{
public override void Up()
{
AddColumn("dbo.BiblRequisicoes", "DataRequisicao", c => c.String(nullable: false, defaultValue: "01/01/1900 00:00"));
}
public override void Down()
{
DropColumn("dbo.BiblRequisicoes", "DataRequisicao");
}
}
And the property to add to the class is the following:
[Required]
[Display(Name = "Data Requisição")]
public string DataRequisicao { get; set; }
When I publish the project and go to the project web site, I get the following error message:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
Inspecting the database, I see that the migration was run with success because the column was created. In the migration table, there also is a new entry that indicates that the migration ran.
The migration entry:
MigrationId: 201704261436437_Add_DataRequisicao_to_BiblRequisicao
ContextKey: WebAppInvestigacaoMultimedia.Migrations.Configuration
Model: 0x1F8B0800000...
ProductVersion: 6.1.3-40302
I don't understand why I get the error message if the migration ran with success and the name and the type of the property is the same as the add column of the table.
This error is usually linked to changes to the model that haven't been added to a migration script yet.
If you look at the folder where you have your migrations, you should have resx files, those files contain a "snapshot" of the model at the time the migration was generated. It therefore knows if there are changes that have been made to the model and will not let you do an Update-Database if there are pending changes.
To resolve the issue, you either have to rollback any changes you made to the model since the last migration you made, or create a new migration using Add-Migration and then do Update-Database.
If you're working with a team, those issues happen sometimes if both you and others have made changes to the model or created migrations. Check this interesting MSDN article to get a few insights on how leverage those issues.

Can't update Database with EF Code-First

I am using EF code-first migrations. I added a new property to my model but it doesn't reflect as a column in the database.
Configuration.cs
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
Global.asax.cs
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, DbMigrationsConfiguration<DbContext>>());
using (var context = new MyDbContext())
{
context.Database.Initialize(true);
}
I have already tried the update-database. It says no pending migrations.
EDIT:
My EF is a separate Class Library Project.
There's another Class Library Project that stores all the Models.
And the Main (Startup) Project is an MVC Project.
Where should I include Migrations?
Also, Add-Migrations Initial always gives me EMPTY Up() and Down() methods.
this worked for me first of all take backup of your database then delete migrations folder in project and delete __MigrationHistory table in database
then run this command
Enable-Migrations -EnableAutomaticMigrations -Force
then add migration
Add-Migration InitialMigration
and finally update database with
Update-Database
Verbose can fix this problem. In your package manager console run
Update-Database –Verbose
Before executing "Update-Database" command did you run "Add-Migrations"?
The Add-Migrations command will generate the necessary migration script to update the database.
Also, do you have a _MigrationsHistory table in your database?
Could you update your code to point to your MyDbContext rather than the base DbContext? And I believe DbMigrationsConfiguration<DbContext>>() should also point to your dbcontext type.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, DbMigrationsConfiguration<MyDbContext>>())
*Add Your New Model Frst: User Model -id,fname,lname,adress,ect...
*Define in your Application db context the new model as a new set Example :
public DbSet Users{ get; set; }
*Create Migration : add-Migration YourMigrationName
*Update Database

Add column to created identity table in asp.net mvc project?

I use identity 2.0 in my MVC 5 project.
First time when I run the project in my DB has been created all default tables for authentication and authorization:
In AspNetUsers table I need to create additional column named LoyoutId of type integer.
My question is how can I add column to created default tables?
You can add profile data for the user by adding more properties to your ApplicationUser class, please visit this to learn more.
In your case:
public class ApplicationUser : IdentityUser
{
public int LoyoutId { get; set; }
}
Then open the Package Manager Console and execute following commands:
PM> Enable-migrations //You don't need this as you have already done it
PM> Add-migration Give_it_a_name //This will generate a database script file
PM> Update-database //Run script file against database.
Now, all the new properties will turn into AspNetUsers table.

EF Code First Database migration error on second start

I have a web application with local database in production environment. In new build I decided to change database and added database migration.
I ran Enable-Migrations in NuGet console.
Program has generated 201410141412423_InitialCreate.cs file as I already had database - there're some code that initialize my database schema.
Then I added one field in model Workstation
public class Workstation
{
public int Id { get; set; }
[StringLength(15)]
public string Name { get; set; }
public DateTime LastCall { get; set; } //this field was added
public string UserConfiguration { get; set; }
private readonly ICollection<StatusBase> _statuses = new Collection<StatusBase>();
public virtual ICollection<StatusBase> Statuses
{
get { return _statuses; }
}
}
I ran Add-Migration WorkstationLastCallAdded command in NuGet console. New file with migration logic was generated with next code:
public partial class WorkstationLastCallAdded : DbMigration
{
public override void Up()
{
AddColumn("dbo.Workstations", "LastCall", c => c.DateTime(nullable: false));
}
public override void Down()
{
DropColumn("dbo.Workstations", "LastCall");
}
}
I also added next code in Global.asax file to update my database
protected void Application_Start()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppDbContext, MigrationConfiguration>());
}
Then I build it and run, and everything works fine.
When I deploy new build to server, there's a database file with some data on the server. The database has old scheme - without LastCall field. So I expect migration updates my database and I won't loose any data.
When I run my site after deploy - everything works fine. Data is not lost and database is updated correctly.
If I restart server or IIS and run my site again - I've got an error.
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
When I open local db and watch _MigrationHistory table - there're two rows with 1410151540264_InitialCreate and 201410141956597_WorkstationLastCallAdded migration id's.
Could anybody help me please? Any ideas what's going wrong? Why it works correctly on first run after update but fails on the second?
Thank you in advance.
IIRC, the answer it pretty simple. You have two migrations:
201410151540264_InitialCreate
201410141956597_WorkstationLastCallAdded
You InitialCreate miration is newer than WorkstationLastCallAdded migration. Why? Because InitialCreate is implicitly added to _MigrationHistory table when your DB is created for the first time and you have no migrations. The timestamp for InitialCreate in this case is, of course, equal to current server time. WorkstationLastCallAdded, on the other hand, has a fixed timestamp which reflects the time when you ran Add-Migration WorkstationLastCallAdded command. Therefore, if you create a database after you've created WorkstationLastCallAdded, InitialCreate will be the 'newest' migration.
What happens next? Db initializer searches for the newest migration and finds InitialCreate. Then it compares InitialCreate model hash with current model hash and sees that these hashes are different (of course they are, you have changed your model!). And then you got your error.
The easiest way to solve this is to rename your WorkstationLastCallAdded timestamp (in migration designer file) to something like this:
99999999999999_0001_WorkstationLastCallAdded
A bunch of nines ensures that this migration is older than InitialCreate. 0001 reflects the order of migration. If you want to create another migration, you should name it like this:
99999999999999_0002_SomeOtherFieldAdded
Hope this helps!

SimpleMembership initializer does not create all the tables

Folks,
After creating a new ASP .NET MVC 4 application, here is what I did:
From the database explorer, deleted all the tables in the default connection.
Edited AccountModels.cs to and added a few more tables.
Updated UsersContext class to reference the new tables:
public class UsersContext : DbCOntext {
...
DbSet<Items> Items {get; set; }
}
Ran the application.
In the debugger, I see that the following line is invoked:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
However, when I look at the database, only the five tables relevant to SimpleMembershipProvider are getting created. My additional tables are not getting created.
I am wondering if there is some step that I missed.
Thank you in advance for your help.
Regards,
Peter
You need to create another DbContext class for your domain model.
Using the same DbContext, UsersContext will cause you many problems in the future. I had so many problems with that. and turned out, you need a seperate DbContext for your domain model.
Thank you for your help. I eventually figured it out. The default InitializeSimpleMembershipAttribute class is geared to create only the required tables (and columns) for simple membership. You create your own initializer class that inherits from CreateDatabaseIfNotExists<>. Now, you can just delete and recreate an empty database. When you run your application, ALL your tables will automatically get created.
Peter

Resources