Unwanted migration for object mapped to view
Problem
We have an object
public class Foo
{
[Key, Column(Order = 0)]public virtual int A { get; set; }
[Key, Column(Order = 1)]public virtual int B { get; set; }
}
which needs to be mapped to an indexed view in SQL Server. Based on approaches
EF Code First: Displaying Non-Bit Objects with Fluent API and StackOverflow question
we first created an initial migration
public override void Up()
{
CreateTable("dbo.Foos",
c => new { A = c.Int(nullable:false), B = c.Int(nullable:false) })
.PrimaryKey(t => new { t.A, t.B });
}
Then an empty migration where we added SQL to drop the auto-generated table and then add the index
public override void Up()
{
Sql(@"DROP TABLE Foos");
Sql(@"CREATE VIEW dbo.Foos As....");
}
finally, in our DbContext, Foo is mapped to the view:
modelBuilder.Entity<Foo>().ToTable("Foos");
This worked great until we added another property to Foo:
[Key, Column(Order = 2)]public int C { get; set; }
We have added a new migration to override the view
public override void Up()
{
Sql(@"ALTER VIEW Foos ....");
}
The Alter View migration is being applied correctly, but EF thinks it should create a migration to account for the new property.
The database cannot be updated 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 migrations.
When I ran
Add-Migration WhatIsPending
EF generates
public override void Up()
{
DropPrimaryKey("dbo.Foos");
AddColumn("dbo.Foos", "C", c => c.Int(nullable: false));
AddPrimaryKey("dbo.Foos", new[] {"A", "B", "C" });
}
Question
Is there a better approach for mapping an object to a view so that changes to the object are painless?
If this is the best approach, how can I tell EF Migrations that it doesn't need to generate a migration?
source to share
We couldn't find a way to tell EF not to create a hyphen, but this approach might help:
-
When you create a POCO, don't follow
CreateTable()
through on the migration. if EF wants to create a migration file, great, but you can comment out the code, so only runsSql(@"Create View ...");
. -
All we had to do was create
DbSet
for the view, notmodelBuilder.Entity
. -
When you need to make changes, run the same path as any other table. Make your changes to the POCO, then run
Add-Migration
and create the migration for you. comment out whatever it wants to do and add yourAlter View
script. Make sure you make the appropriate one inDown
.
This way you will only have one migration file for each change.
source to share