EF Core 2.1 +数据库视图

1.参考文档

https://stackoverflow.com/questions/36012616/working-with-sql-views-in-entity-framework-core

https://docs.microsoft.com/en-us/ef/core/modeling/query-types

Step 1:

首先数据库新建一个 View视图,咱们称之为"V_USer_FromHRM".

Step 2:

项目中新建一个Model 与视图查询结果相对应。

 1 public class V_HRMUser
 2     {
 3         public V_HRMUser()
 4         {
 5 
 6         }
 7 
 8         public string Empl_code { get; set; }
 9         public string Sitecode { get; set; }
10         public string Department { get; set; }
11         public string Function { get; set; }
12         public string Position { get; set; }
13    
14 
15     }

 

Step3:

Dbconext中添加如下代码(涉及项目内容,代码有删减,看得明白就好):)

 1 public class DefaultDbContext : DbContext
 2     {
 3         public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
 4         {
 5             
 6         }
 7 
 8        
 9 
10         public  DbQuery<V_HRMUser> V_HRMUsers { get; set; }
11 
12        
13 
14         protected override void OnModelCreating(ModelBuilder modelBuilder)
15         {
16            //不必太在意字段信息,涉及到项目内容,已经做了删改。
17             modelBuilder.Query<V_HRMUser>(v => { 
18             v.ToView("V_USer_FromHRM");
19                 v.Property(p => p.Department).HasColumnName("department");
20                 v.Property(p => p.Empl_code).HasColumnName("empl_code");
21                 v.Property(p => p.EmpType).HasColumnName("emptype");
22                 v.Property(p => p.Ename).HasColumnName("ename");
23              
24               
25            
26             }
27             );
28         }
29 
30     }

 

Step 4:

测试结果:

随便找个 Controller ,

 public class HomeController : BaseController
    {
        private DefaultDbContext _context;
        public HomeController( DefaultDbContext context)
        {
            _context = context;
            var list = _context.V_HRMUsers.ToList();
        }
}

 

结果:

 

 

To DO

1.类型转换转换问题。

2.数据是只读的,有没有更好的读取方式? 

3.缓存?

 

posted @ 2018-11-06 15:35  春秋一梦  阅读(1836)  评论(0编辑  收藏  举报