In a newly created MVC4 web project, I delete a table in the Server Explorer (DataConnections…. with Mouse’s Right Click), then in the Package Manager Console (PMC) I run
update-database -verbose -force
to generate a new table of the same name in the same database. But the PMC only tries out “ALTER” command which is not what I would want it to do and it outputs an error
Cannot find the object “dbo.UserProfile” because it does not exist or
you do not have permissions.
How can it fix this now ?
UPDATE
Here is the data model of the class UserProfile
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
[DefaultValue(false)]
public bool IsActivated { get; set; }
}
And here is the code to initialize the table in the Seed method of the Configuration file
WebSecurity.CreateUserAndAccount("Administrator", "admin",
new
{
UserEmail = "admin@gmail.com",
IsActivated=true
}
);
EF Migrations expects that either you are in charge (you can use the -Script option to have Migrations generate scripts rather than run DDL directly), or that it is in charge. Mixing and matching does not work.
If you know the structure of UserProfile (perhaps you saved a script?) you can manually re-create it as it was before your change, then allow EF Migrations to apply the migration again.
If you have an appropriate backup of the database, restore that and retry.
If not, you can drop and re-create the database, then do an initial migration.
Personally I always have EF Migrations script the migrations (-Script option). I then apply the script myself. That way, I have everything I need to do a controlled migration in QA and PROD environments. I just don’t have enough trust in EF Migrations to let it auto migrate production data (not that Migrations is bad, but a minor bug could wipe out production data. Not a risk I’m willing to take.)