關於EF延時加載的面試題

   public async Task<ActionResult> GetData()
   {
       var data = (from leftdata in GetLeft()
                   join rightdata in GetRight() on leftdata.Id equals rightdata.Id into tempdata
                   from matchdata in tempdata.DefaultIfEmpty()
                   select matchdata).ToList();
       return Ok(data);
   }

   
   private IEnumerable<YourModel> GetLeft()
   {
       return YourDbContext.YourModels.Where(c=>c.Id==1);
   }
   private IEnumerable<YourModel> GetRight()
   {
       return from data in YourDbContext.YourModels
              select data;
   }

上面代碼調用GetData()查詢了幾次數據庫?

如果換成IQueryable又如何

 public async Task<ActionResult> GetData()
 {
     var data = (from leftdata in GetLeft()
                 join rightdata in GetRight() on leftdata.Id equals rightdata.Id into tempdata
                 from matchdata in tempdata.DefaultIfEmpty()
                 select matchdata).ToList();
     return Ok(data);
 }

 
 private IQueryable<YourModel> GetLeft()
 {
     return YourDbContext.YourModels.Where(c=>c.Id==1);
 }
 private IQueryable<YourModel> GetRight()
 {
     return from data in YourDbContext.YourModels
            select data;
 }

使用IQueryable查詢了一次數據庫,IEnumerable查詢了兩次

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章