为什么一个简单的LINQ命令没有在第二情况下执行? [英] Why a simple linq command is not executed at the second case?

查看:125
本文介绍了为什么一个简单的LINQ命令没有在第二情况下执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我下面的代码行。

I have the following line at my code.

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



不过,我认为该命令
query.Min(Y => y.Date)
是每x执行。

However I think that the command query.Min(y => y.Date) is executed for every x.

所以,我要做到以下几点

So I want to do the following

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

在我的模型字段的类型日期是 System.DateTime的。

The type of the field Date at my model is System.DateTime.

然而,如果我改变它的第二种方式,这我得到一个异常

However, If I change it at the second way, It I get an exception

An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

修改

上面提到的查询是以下

var query = (from b in db.StudentProgressPerDay
                         where b.Student.Equals(InputStudent)
                         orderby b.Date
                         select b);



这是为什么?和我如何解决?

Why is that? And how I can fix it?

推荐答案

没有它只做了一次,做 query.ToString ()我们可以看到SQL实体框架是将要发生。您的查询生成以下SQL

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]

你可以看到它做一个查询,以获得最低值,那么它加入该查询的结果你的 DATEDIFF 在那里将一遍又一遍地重复使用单一的结果。

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.

测试程序

class Context : DbContext
{
    public DbSet<Foo> 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();
        }
   } 
}

这篇关于为什么一个简单的LINQ命令没有在第二情况下执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆