#Creating a SQL View w/ Entity Framework
- Create an entity with the proper format (matching the columns, properties, etc., of your SQL View).
- Add an entry to your
DbContext
similar to any other entity; e.g.public DbSet<MyView> MyViews { get; set; }
- Run
Add-Migration CreateMyViews
(name is irrelevant, but try to describe what you're doing: Creating a new view). - Alter the migration so that it instead creates your SQL view,
Sql(@"create view MyView as (your select here)");
- Note: put a
@
before your string to allow it to run along multiple lines
- Run
Update-Database -Force
It's important to do this in this order! Creating the migration with the entity registered with DbContext
first will allow EF to think the db is properly updated once the explicit migration runs -- and it will NOT try to create a table called MyView
, which is the default behavior -- even if there is already a View in place.