How to use SQL Server Views with EF Code First Mig

2019-07-15 10:35发布

问题:

I've reverse engineered a small database that contains a number of tables and views into EF 5 code first.

When I do this, I get a set of models and mapping classes for each of my tables and these work well when I try to query the database using the generated DbContext.

It also generates POCO classes for each of my views, but when I run Enable-Migrations and Add-Migration using the Package Manager Console, the migration does not re-create the SQL Server views.

I have tried updating the migration manually to create the views using custom SQL like so:

Sql("CREATE VIEW [dbo].[viewUsersDeactivated] "
          + "AS "
          + "SELECT ... ");

This works fine when I run Update-Database, but the SQL script that is output from the Update-Database -Script command does not seem to be valid, resulting in the following error:

'CREATE VIEW' must be the only statement in the batch.

Inserting Sql("GO"); between each of the custom SQL statements works for the script generation, but then I can no longer update using Update-Database, and I can't find a way that works for both.

So my question boils down to: How can I include SQL Server views in a code first migration script such that I can create a database both using Update-Database and via production scripts generated using Update-Database -Script?

Thanks!

回答1:

Not entirely sure this is best practice, and someone else might have a better solution, but I got around this by wrapping the entire view creation script in an Execute, thus:

var sql = "CREATE VIEW [dbo].[TheViewName] AS ......."
sql = sql.Replace("'", "''"); // sanitize the sql string
sql = string.Format("EXECUTE sp_executesql N'{0}'", sql);
Sql(sql);