Skip to content

Instantly share code, notes, and snippets.

@cscott530
Last active August 29, 2015 14:27
Show Gist options
  • Save cscott530/455755cd9ff45dacb722 to your computer and use it in GitHub Desktop.
Save cscott530/455755cd9ff45dacb722 to your computer and use it in GitHub Desktop.
Creating EF Views

#Creating a SQL View w/ Entity Framework

This is assuming you've already gotten the SQL that drives the view written.

  1. Create an entity with the proper format (matching the columns, properties, etc., of your SQL View).
  2. Add an entry to your DbContext similar to any other entity; e.g. public DbSet<MyView> MyViews { get; set; }
  3. Run Add-Migration CreateMyViews (name is irrelevant, but try to describe what you're doing: Creating a new view).
  4. 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
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment