EFCore使用過程中鏡像查詢,lazyloading,上下文資源池等記錄
1.efcore使用過程中的查詢,一般都會直接去庫鏡像中查找,要避免鏡像查詢數據,在查詢中可以使用AsNoTracking(),讓查詢直 接從數據庫查詢避免鏡像查詢,例如DbContext.Product.AsNoTracking().ToListAsync().
2.efcore使用過程中,如果緩存鏡像已緩存了數據,可以使用FindAsync()直接從鏡像緩存中查詢數據,避免直接查詢數據庫。例 如:_context.Products.FirstOrDefaultAsync(m => m.Id == id),可以修改爲_context.Products.FindAsync(id).
3.efcore 提供兩種加載方式一種是eager loading 另一種是lazy loading.要使用eager loading加載對象集合數據可以對查詢添加 Include().例如:_context.Products.Include(p=>p.ProductOrders).FindAsync(Id).
而lazyloading 1.需要添加nuget包:Microsoft.EntityFrameworkCore.Proxies. 2.服務配置對於options的添加 UseLazyLoading():例如:services.AddDbContextPool<ContosoPetsContext>(options => options.UseLazyLoadingProxies().UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ContosoPets;Integrated Security=true")); 3.對於entity類型中的集合得用virtual進行修飾例如: public virtual ICollection<ProductOrders> ProductOrders { get; set; }
4.DbContext經常創建釋放問題,可以使用上下文池,例如:將 services.AddDbContext修改爲使用資源池 services.AddDbContextPool。