Reputation: 150108
I have a class something like
public class Foo
{
public virtual string Bar { get; set; }
// Other Stuff
}
It is now necessary to treat Bar
like a CHAR(8) so I modified the property to
[StringLength(8)]
[Column(TypeName = "char")]
public virtual string Bar { get; set; }
There are many migrations in the project, generally that add new classes or new properties to existing classes. I know I could just generate a new migration that changes the column type, but it seemed a bit convoluted to initially create the column as NVARCHAR(Max) and then change it to CHAR(8). I edited the initial migration, changing
CreateTable(
"dbo.Foo",
c => new
{
Bar = c.String(),
// Other stuff
})
to
CreateTable(
"dbo.Foo",
c => new
{
Bar = c.String(maxLength: 8, fixedLength: true, storeType: "char", unicode: false),
// Other stuff
})
I then deleted the database and ran a program that used the context, thus re-creating the database.
I set a breakpoint in that initial migration and also at the end of the last migration. As soon as the initial migration completes, the table Foo is created in the newly re-created database with the expected column type CHAR(8). After the final migration completes and I attempt to use the context, I get an AutomaticMigrationsDisabledException
.
I then scripted a migration to see what EF things the differences are, and get
public override void Up()
{
AlterColumn("dbo.Foo", "Bar", c => c.String(maxLength: 8, fixedLength: true, unicode: false));
}
public override void Down()
{
AlterColumn("dbo.Foo", "Bar", c => c.String());
}
The Up() migration is doing what was already done when the table was created (and physically matches the schema), while the Down() migration wants to change the column back NVARCHAR(Max), which it never was.
Question
Why does EF attempt to perform this seemingly unnecessary migration, and can I alter the column type without first creating the NVARCHAR(Max) and then changing it to CHAR(8) in a new, separate migration?
Upvotes: 4
Views: 203
Reputation: 12304
This link describes the internals of the migration process. The issue here has to do with the comparison model that is embedded in a resource file for the migration being generated at creation time. If you change the Up() Down() code you can affect the generated script, but not the initial comparison model.
It is not advised to change these models, although this link shows how you can inspect it. The advised workaround is to create a new migration so the model is inserted into it's resource file. Use the -IgnoreChanges flag to create a blank migration with just a model update. See https://msdn.microsoft.com/en-us/data/dn579398.aspx?f=255&MSPPError=-2147217396#option1
Upvotes: 2