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