Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a database view using Entity Framework 4 Code-First?

How do I define a database view using Entity Framework 4 Code-First? I can't find anything about this anywhere!

like image 537
Ian Warburton Avatar asked May 04 '11 21:05

Ian Warburton


People also ask

How do you implement database views using Entity Framework EF code First approach?

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.

How do I add a view in Entity Framework?

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.

How do I create a view using EF code First poco?

You cannot create a view from EF Code First ,you should add the script in the 'seed' script to pre populate the view .

How do I use code first in Entity Framework?

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…


1 Answers

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.

like image 94
Ladislav Mrnka Avatar answered Oct 12 '22 00:10

Ladislav Mrnka