如何使用 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您无法使用代码优先方法定义数据库视图。数据库视图是在现有表/函数之上使用 SQL 查询的数据库构造。您不能首先使用代码定义此类构造。
如果您想要视图,则必须通过执行
CREATE VIEW
SQL 脚本(例如在自定义初始值设定项中)手动创建它 - 它将类似于 此答案。请注意,如果您想将实体映射到视图,这对您没有帮助。在这种情况下,您可能必须首先删除 EF 创建的表并创建具有相同名称的视图(我没有尝试,但它可以解决问题)。另请注意,并非每个视图都是可更新的,因此您很可能会获得只读实体。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.要创建视图,您需要创建模型,然后在初始化程序中运行 SQL 语句,使用第一行代码直接针对上下文创建视图,然后在上下文中重写 OnModelCreating 并运行第二行代码以忽略模型。
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.