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.缓存?

 

转载于:https://www.cnblogs.com/kim-meng/p/9915595.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值