gpt4 book ai didi

sql-server - LINQ to SQL 数据上下文日志不显示 WHERE 子句

转载 作者:行者123 更新时间:2023-12-03 00:13:56 26 4
gpt4 key购买 nike

以下是两种情况下的 C# 代码和在 LINQ to SQL 查询中生成的 SQL。

案例1

using (JulianDataContext dc = new JulianDataContext(this.CurrentConnectionString))
{
#if DEBUG
dc.Log = new DebugTextWriter();
#endif

IEnumerable<UserNewsfeedDeliveryTime> temp = dc.UserNewsfeedDeliveryTimes.Where(u => u.NewsfeedEmailPeriodicity > 0 && DateTime.Today >= u.NextNewsfeedDelivery.Value.Date);

ids = temp.Select(p => p.Id).ToList();
}

SELECT [t0].[Id], [t0].[NewsfeedEmailPeriodicity], [t0].[LastSentNewsfeedEmail], [t0].[NextNewsfeedDelivery]
FROM [dbo].[UserNewsfeedDeliveryTimes] AS [t0]
WHERE ([t0].[NewsfeedEmailPeriodicity] > @p0) AND (@p1 >= CONVERT(DATE, [t0].[NextNewsfeedDelivery]))
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [0]
-- @p1: Input DateTime (Size = -1; Prec = 0; Scale = 0) [15-11-2012 00:00:00]

案例2

using (JulianDataContext dc = new JulianDataContext(this.CurrentConnectionString))
{
#if DEBUG
dc.Log = new DebugTextWriter();
#endif
IEnumerable<UserNewsfeedDeliveryTime> temp = dc.GetTable<UserNewsfeedDeliveryTime>();

temp = temp.Where(u => u.NewsfeedEmailPeriodicity > 0 && DateTime.Today >= u.NextNewsfeedDelivery.Value.Date);

ids = temp.Select(p => p.Id).ToList();
}
SELECT [t0].[Id], [t0].[NewsfeedEmailPeriodicity], [t0].[LastSentNewsfeedEmail], [t0].[NextNewsfeedDelivery]
FROM [dbo].[UserNewsfeedDeliveryTimes] AS [t0]

区别

这两个 linq 查询之间的区别:

dc.UserNewsfeedDeliveryTimes

dc.GetTable ()

为什么?难道在情况2中,LINQ to SQL正在从数据库中检索所有数据并通过过滤内存中的所有对象来完成查询?

如果是这样,我们如何才能保持这种通用性并仍然强制生成所有 T-SQL?

解决方案

两个答案都是正确的,但我必须选择一个,抱歉!我认为在这种情况下添加这一点也很有趣,因为我更改为使用 IQueryable(继承自 IEnumerable),在这一行中:

temp = temp.Where(u => u.NewsfeedEmailPeriodicity > 0 && DateTime.Today >= u.NextNewsfeedDelivery.Value.Date);

我有两种重载方法,一种来自 IQueryable 接口(interface),另一种来自 IEnumerable 接口(interface)。

public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

所以我必须将我的谓词显式转换为 Expression> 谓词,否则 IEnumerable 接口(interface)方法将在编译时被选取,如果我没有记错的话,我会得到一些动态 sql 异常,说 T-SQL 可以尚未生成。

最佳答案

据我了解,IEnumerable 不会转换 IQueryable 所保存的原始查询信息。这几乎就像转换在转换时卡住了对 IQueryable 查询的任何更改一样。如果你查看 MSDN,就会发现 IQueryable 继承了 IEnumerable:

http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx

因此,您会看到这种行为。 LINQ-SQL 与 IQueryable 配合使用非常重要,除非您希望查询在转换为 IEnumerable卡住。 p>

在第一个示例中,where 包含原始查询。 select 并不是生成的查询。

在第二个示例中,您将表本身捕获到 IEnumerable 中。除此之外的任何更改都在内存中原始查询之上完成。

当你想到时,whereIEnumerable 版本将无法转换 IQueryable 的原始数据,因为转换和继承是如何工作的。

当您还考虑延迟加载以及 LINQ 的工作原理时,这似乎是有道理的。对我来说,这是一个很大的烦恼,因为它可能会导致您生成一些性能糟糕的代码。

关于sql-server - LINQ to SQL 数据上下文日志不显示 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com