如何使用Entity Framework 4 Code-First定义数据库视图?

如何使用Entity Framework 4 Code-First定义数据库视图?

问题描述:

如何使用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!

这是因为您无法使用代码优先方式定义数据库视图。数据库视图是在现有表/函数之上使用SQL Query的数据库构造。您不能使用代码首先定义这样的构造。

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.

如果要查看,您必须通过执行 CREATE VIEW SQL脚本,例如在自定义初始化程序中 - 它将类似于此答案。只要注意,如果要将实体映射到视图,这将无法帮助您。在这种情况下,您可能必须首先删除由EF创建的表并创建具有相同名称的视图(我没有尝试,但它可以做的伎俩)。还要注意,并不是每个视图都是可udpatable,所以你最有可能获得只读实体。

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.