EF: Automatic migrations are running when disabled - entity-framework

I'm trying to update the database on a build server, and it's failing because it's trying to run automatic migrations, even though they're disabled. The database already exists and I just need to apply the latest migration. Here's my context:
public sealed class Configuration : DbMigrationsConfiguration<CableSenseInstanceConfiguratorContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
I've got a bunch of migration files I've created manually, here's the latest one:
public partial class Settings : DbMigration
{
public override void Up()
{
AddColumn("dbo.MasterInstances", "Settings", c => c.String());
}
public override void Down()
{
DropColumn("dbo.MasterInstances", "Settings");
}
}
If I then manually update the database from the package manager console, I see it tries to run an automatic migration (which fails because the table already exists):
Applying code-based migrations: [201204200805145_NoMoreCerts, 201210311451543_SuperUsers, 201301041036414_Settings, 201301041128583_Settings2].
Applying code-based migration: 201204200805145_NoMoreCerts.
Applying automatic migration: 201204200805145_NoMoreCerts_AutomaticMigration.
My __MigrationHistory table just has the one entry for the initial creation. How can I stop it from doing the automatic migrations?

Check out the answer from jjslagace here:
Update-Database tries to do an automatic migration even with automatic migrations disabled
You are building your migrations manually. My guess is entity framework wants to add something that you don't have in your migration script, or it wants to name columns differently etc. EF has a brain, and that brain is fairly simple. It's expecting things to be a certain way unless you tell it otherwise using fluent (not by manually creating/tweaking migration files). From the answer on the question above it sounds like sometimes that results in the issue you are seeing.
Long story short don't build the migration files manually. Instead run the add-migrations command. This will create the migration for you and you can see what EF is expecting to do before it's applied to your database (because sometimes it's stupid). If you need to override what EF is generating for you add a fluent mapping in your DBContext class by overriding OnModelCreating. Then just run add-migration again with the -force option. Here is a good reference for using the Fluent API to custimize EF mappings. Rinse and repeat until you get the migration you are looking for then run update-database.
Hope that helps!

Related

Identity 2.0 CodeFirst Migration to Use Stored Procedures

I'm trying to move my existing ASP.Net Identity Framework project across to use Stored Procedures on the existing models. I have migrations already enabled, and have an existing database which is basically the stock/standard the Identity builds (few extra columns here and there). I have tried to enable the Stored Procedures via the DbContext:
public class IdentityDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().ToTable("Users").MapToStoredProcedures();
modelBuilder.Entity<ApplicationRole>().ToTable("Roles").MapToStoredProcedures();
}
}
Then I generate the migration:
Add-Migration -Name AddStoredProcedures
And apply the migration:
Update-Database
Now when I try to run my application I am getting the exception when it attempts :
System.InvalidOperationException: The model backing the 'IdentityDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)."}
AFAICT, I ran the update correctly (__migrationhistory table contains the name of the migration). Looking at my database, the stored procedures are added. Why does the framework not recognize it?

How to create spatial index using EF 6.1 fluent API

Well, the question is clear enough. Is it possible to create spatial indexes using Entity Framework 6.1 fluent API?
The only way I know to do this is through a "custom" migration. In EF6, I add a migration (in the example below it's named "V1"), resulting in an new migration with empty Up() and Down() methods. You can then add custom SQL commands to these methods before running update-database to put these in the "normal" migrations flow.
It's possible to modify an existing migration to add these features, but I prefer in practice to keep my automatically scaffolded migrations separate from my customized ones.
public partial class V1 : DbMigration
{
public override void Up()
{
Sql("CREATE SPATIAL INDEX [IX_UserProfileAddresses_Location] ON [dbo].[UserProfileAddresses](Location)");
}
public override void Down()
{
Sql("DROP INDEX [IX_UserProfileAddresses_Location] ON [dbo].[UserProfileAddresses]");
}
}
Not an ideal method, but not too bad since it does follow the "normal" migrations pattern for EF.
Short answer- No, it is not. I have seen this tangentially referenced throughout blogs and have found no concrete examples of implementation. It seems to be related to the fact that spatial indexes are filtered indexes, which are not supported in Entity Framework.
As support for my answer I constructed a POC console app with the most recent version of Entity Framework (6.1). I took the following steps
Created a model that had a property of the type DbGeography
Enabled automatic migrations
Ran Update-Database -verbose insuring migration with the addition of an index was run. The index used the following:
modelBuilder.Entity<LocationEntity>().Property(t => t.Coordinates).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("ix_locationentity_coordinates")));
No indexes were created, but neither did the app crash. I could try permutations on this, but my example seems to follow the convention of entity framework: Official Fluent Documentation

How do I use Entity Framework in Code First Drop-Create mode?

I'm using Entity Framework v4. I have followed the instructions in the Nerd Dinner tutorial. I'm currently in development mode (not released to any higher environments) and would like for tables to be recreated on each new deployment, since the models are still highly volatile and I don't care to retain data. However, this does not occur. Tables are not created/modified, or anything happening to the DB. If I move to a migrations model by using the Package Manager commands: enable-migrations, add-migration (initial), this works and uses my migrations. However, since I don't yet want to have granular migrations and only want my initial create script, I am forced to delete the migrations folder, redo the commands (enable-migrations, add-migration) and delete the database manually, every time I change anything.
How do I get the drop/create behavior of code first to occur?
Use DropCreateDatabaseAlways initializer for your database. It will always recreate database during first usage of context in app domain:
Database.SetInitializer(new DropCreateDatabaseAlways<YourContextName>());
Actually if you want to seed your database, then create your own initializer, which will be inherited from DropCreateDatabaseAlways:
public class MyInitializer : DropCreateDatabaseAlways<YourContextName>
{
protected override void Seed(MagnateContext context)
{
// seed database here
}
}
And set it before first usage of context
Database.SetInitializer(new MyInitializer());
If the database already exists and you want to make changes to your model, you use DropCreateDatabaseIfModelChanges<YourContextName>

How to recreate my EF CodeFirst Table?

I created a Code First class
A database was created in Sql automatically.
I deleted the tables :(
I have migrations enabled:
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
Database.SetInitializer(new DropCreateDatabaseAlways<SurveyContext>());
Yet upon
update-database -force
Cannot find the object "dbo.CustomerResponses" because it does not exist or you do not have permissions.
Please help.
In system tables there is a table called
__MigrationHistory
...I deleted it.
In Package manager console ran command "update-database"
Problem fixed!
More info:
http://blog.oneunicorn.com/2012/02/27/code-first-migrations-making-__migrationhistory-not-a-system-table/
Daf De Giraf has a better answer here that doesn't wipe out your migration history.
If you worked the correct way to create your migrations by using the
command Add-Migration "Name_Of_Migration" then you can do the
following to get a clean start (reset, with loss of data, of
course):
Update-database -TargetMigration:0
Normally your DB is empty now since the down methods were executed.
Update-database
This will recreate your DB to your current migration
I had that error message in the past....
Check if the database that you've specified in the connection string is created. If it's not, create it and then execute the code.
Obviously there may be a better way of doing this, but as this was surprisingly top Google account I thought it would be good to mention the idea i had after reading these answers:
Here's the issue i faced:
I was changing FK's generated by EF6 code first and came across the error:
Unable to determine the relationship represented by navigation property 'Account.SalaryIncomes' of type 'ICollection<Person>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
I attempted many ways of defining the Mapping in the hopes of resolving this error, however i ended up dropping my Person table, and after removing the the relationship entirely in an attempt to start from scratch, the error was resolved. However when updating the database, it complained that "Person" did not exist - which lead me here.
After reviewing these answers, I decided I was too lazy to reload the data and thought that the migrations generated C# UP() and Down() methods - I thought, maybe i can reference another migration...
after extracting the up and down code into public methods in that migration, and referencing those from the new migration - the update worked and person was then created. Just to be safe - i wrapped the new calls in try catch... do my new UP method looks like this:
protected override void Up(MigrationBuilder migrationBuilder)
{
try
{
new AddPeople().CreatePersonTable(migrationBuilder);
}
catch { }
// Origional generated migration code
}
This answer comes with the caviat that I have not tested to see if this migration will be overridden next time (loosing the code) - however if the migrations are run in order, then pressingly you can in fact run this once, and then remove it after.

How to disable migration in Entity Framework 4.3.1?

Is there any way to disable migration in Entity Framework 4.3.1? I removed the migrations folder from the project and the generated tables in my database, but it doesn't work! How can you remove the migration?
If you don't want to use migrations but in the same time you want EF to create database for you, you just need to set correct database initializer:
Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists<YourContentType>());
Deleting the Migrations folder has worked for me. I don't get any errors, it puts me back to where I started.
The way that I got around this was to make sure that I turned off Automatic Migrations in my code:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
and then I deleted the _MigrationHistory table from the database (this is usually created as a system table if you can't find it)