How do I define a database view using Entity Framework 4 Code-First? I can't find anything about this anywhere!
You cannot create views with EF Code First approach. If you want to create view then execute creation sql script in Seed method. But you'll still not be able to map entity to this view, except hacking model by creating and droping table with same name as your view will have.
Step 1 − Create a new Console Application project. Step 2 − Right-click on project in solution explorer and select Add → New Item. Step 3 − Select ADO.NET Entity Data Model from the middle pane and enter name ViewModel in the Name field. Step 4 − Click Add button which will launch the Entity Data Model Wizard dialog.
You cannot create a view from EF Code First ,you should add the script in the 'seed' script to pre populate the view .
Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
That's because you cannot define database view using code-first approach. Database view is database construct which uses SQL Query on top of existing tables / functions. You can't define such constructs using code first.
If you want view you must create it manually by executing CREATE VIEW
SQL script for example in custom initializer - it will be similar like this answer. Just be aware that this will not help you if you want to map entity to a view. In such case you would probably have to first drop table created by EF and create view with the same name (I didn't try it but it could do the trick). Also be aware that not every view is udpatable so you will most probably get read only entity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With