Mapping Database Views to EF 5.0 Code First w/Migrations

You have specified that the ClientStatisticsView entity should be mapped to a table named “ClientStatistics”. So entity framework will generate a migration containing an instruction to create that table. But you have independently created that view in the database so to prevent the error you are getting you should remove the CreateTable instruction from the Up migration.

I think a better way to do it is to create the view in the migration by running sql like this:

public override void Up()
{
    Sql("EXEC ('CREATE View [dbo].[ClientStatistics] AS --etc"
}

public override void Down()
{

    Sql(@"IF  EXISTS (SELECT
                        *
                    FROM sys.views
                    WHERE object_id = OBJECT_ID(N'dbo.ClientStatistics'))
                    DROP VIEW dbo.ClientStatistics)")
}

That way your views and tables are specified in one place and you can safely migrate up and down

Reference

http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

Leave a Comment