Create Database Views using EF Core Code First approach

entity-framework entity-framework-core

Question

I am working on a new application that requires, the creation of DB Views. I am using EF core with MySql flavor and using the Code First approach to create the DB and tables. I didn't find a way to create a view though.If somehow, I could execute the raw sql in migration step, that might help in creation of view and later mapping that as the DbSet. I can't create the views manually as it would require the execution of the view script against the database, and that won't be possible in higher environment. Can someone please guide me. Help is really appreciated!

1
3
11/4/2019 1:00:04 PM

Popular Answer

As far as I know, you can't create views with EF Core directly. However, you can use migrations to execute arbitrary SQL when upgrading.

  1. Generate a migration in the package manager console, even if there is nothing really to do: add-migration CreatingTheView
  2. Open the generated migration class, file name: Migrations\yyyyMMdd_CreatingTheView.cs
  3. Add raw SQL to execute when upgrading by modifying the Up method: migrationBuilder.Sql("CREATE VIEW etc.");
  4. If you want to support downgrading, modify the Down method: migrationBuilder.Sql("DROP VIEW etc.");
6
11/4/2019 1:08:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow