Differences when using IEnumerable and IQueryable as a type of ObjectSet

前端 未结 4 505
小蘑菇
小蘑菇 2021-02-09 08:19

As I understand it when I use LINQ extension methods (with lambda expression syntax) on IQueryable that is in the fact instance of ObjectSet they are t

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-09 08:46

    Undeleting my answer because I just tested it and it works exactly as I described:

    None of mentioned queries will hit the database because there was no enumeration. The difference between IQueryable query and IEnumerable query is that in the case of IQueryable the filtering will be executed on the database server whereas in the case of IEnumerable all objects will be loaded from the database to a memory and the filtering will be done in .NET code (linq-to-objects). As you can imagine that is usually performance killer.

    I wrote simple test in my project:

    [TestMethod]
    public void Test()
    {
        // ObjectQuery converted ot IEnumerable
        IEnumerable departmetns = CreateUnitOfWork().GetRepository().GetQuery();
        // No query execution here - Enumerable has also deffered exection
        var query = departmetns.Where(d => d.Id == 1); 
        // Queries ALL DEPARTMENTS here and executes First on the retrieved result set
        var result = departmetns.First(); 
    }
    

提交回复
热议问题