How to use SQL Server Views with EF Code First Migrations

会有一股神秘感。 提交于 2019-12-11 02:57:47

问题


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);


来源:https://stackoverflow.com/questions/13801982/how-to-use-sql-server-views-with-ef-code-first-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!