数据库视图 (View)和EntityFramework Code First结合使用

问题来源:

项目需要进行查询操作,会涉及多表间的联合查询,使用Entity Framework会牵涉到效率问题,为增加查询速度,所以使用数据库视图技术,综合来讲是将Model类映射到数据库View。

来自MSDN的一篇文章Mapping to an Indexed View :

1) You can certainly use Code First to map to a view, just tell Code First that it's a table and it will use the same SQL against the view that it would for a table. Obviously if your view isn't writeable then saving is going to fail if you try and update values in the entities that are based on the view, but we will just delegate to the database so if you don't update these entities then you won't have any issues.

2) You don't need to have a foreign key in the database, Code First will assume you have one, but in this case that won't cause any issues because there will always be a matching customer for each row anyway. You will need to give Code First a valid primary key for the view, which sounds like it would be customer_id and currency_code in your case.

但该文章并未指出该如何实现Model类到已存在View的映射。

1、首先生成POCO实体类;

2、数据库底层访问实现,主要是OnModelCreating方法的书写

3、实现访问

此过程大致类似于Entity Framework Code First执行SQL语句、视图及存储过程,实现过程中仍会存在问题,关键点如下:

Key Point:生成POCO对象后,数据库会显示需要进行数据库升级,需要先将数据库升级,然后将新生成的Table删掉,生成视图与删掉的Table名称相同,此时POCO对象对应的就是视图View,由于视图的生成更新是由数据库自动完成,所以不能进行全部CRUD操作。