Why a simple linq command is not executed at the second case?

后端 未结 1 1907
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 22:42

I have the following line at my code.

var dates = query.Select(x => EntityFunctions.DiffDays(query.Min(y => y.Date), x.Date));

Howev

1条回答
  •  心在旅途
    2021-01-18 23:07

    No it only does it once, by doing query.ToString() we can see the SQL Entity Framework is going to be generating. Your query generates the following SQL

    SELECT 
        DATEDIFF (day, [GroupBy1].[A1], [Extent1].[Date]) AS [C1]
        FROM  [dbo].[Foos] AS [Extent1]
        CROSS JOIN  (SELECT 
            MIN([Extent2].[Date]) AS [A1]
            FROM [dbo].[Foos] AS [Extent2] ) AS [GroupBy1]
    

    You can see it does a single query to get the minimum value then it joins the result of that query to your DATEDIFF where it will reuse that single result over and over.


    The test program

    class Context : DbContext
    {
        public DbSet Foo { get; set; }
    }
    
    public class Foo
    {
        public int FooId { get; set; }
        public DateTime Date { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new Context())
            {
                var query = context.Foo;
                var dates = query.Select(x => EntityFunctions.DiffDays(query.Min(y => y.Date), x.Date));
    
                var result = dates.ToString();
    
                Debugger.Break();
            }
       } 
    }
    

    0 讨论(0)
提交回复
热议问题