How do I define a database view using Entity Framework 4 Code-First? I can't find anything about this anywhere!
2 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.

- 1
- 1

- 360,892
- 59
- 660
- 670
-
Yes you're right. In fact I've realised that there's not really much point in defining a view in code. :) – Ian Warburton May 05 '11 at 08:33
-
2I implemented the "drop the table and add a view" in the initializer of a project when using EF to build the database. Not much fun but it does work. Where that would leave you with Migrations is an open issue. I'm contining to look for a cleaner way to tell EF Code First *not* to generate a particular table. – jlo Jun 07 '12 at 18:15
-
2@Ladislav And that's why this new EF code-first framework is only viable if your application hold no complexity and doesn't really do anything except house data. If the application actually does something - you're going to have to stick with the EDMX or some other ORM system of your choice. – Mike Perrenoud Jun 19 '12 at 11:23
-
EDMX Model First is no better imo since if you import a view, you get a table when you "Generate Database from Model". Same problem. Both need an official concept of a view vs. table. – Dave Feb 19 '14 at 23:00
To do a view you create the model, then in the initializer you run the SQL statement to create the view directly against the context with the first line of code, and then in the context you override OnModelCreating and run the second line of code to ignore the model.
context.Database.ExecuteSqlCommand(Resources.<resourcename>);
modelBuilder.Ignore<modeltype>();

- 66,820
- 29
- 157
- 232
-
5This works and I like it because it removes the need to drop an EF-created table. But it should be noted that this way you cannot use the view in your EF-model. – Stephan Keller Jun 19 '12 at 10:20
-
3@StephanKeller That is correct, and in the end I ended up having to go back to an old fashioned EDMX because of the limitations of the EF code-first approach. To be honest, if your application does anything, you're not going to be able to use the EF code-first approach. But in the end that shouldn't be that surprising because automation can only go so far. So +1 for that. – Mike Perrenoud Jun 19 '12 at 11:20