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

蹲街弑〆低调 提交于 2019-12-17 07:33:28

问题


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


回答1:


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.




回答2:


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>();


来源:https://stackoverflow.com/questions/5889905/how-do-i-define-a-database-view-using-entity-framework-4-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!