【问题标题】:Linq to Sql escape WHERE clauseLinq to Sql 转义 WHERE 子句
【发布时间】:2015-08-29 05:40:24
【问题描述】:

我有这个 Linq-to-SQL 查询

  DaynamicContext.Log = new System.IO.StreamWriter("f:\\linq-to-sql.txt") { AutoFlush = true })
  var tt = DaynamicContext.GetTable(tbl);
  var query = ((from c in tt where c.IsDeleted != true select c.Id).Take(1)).ToList();

最终查询的结果是正确的,只有一个Id。

当我有大数据时出现内存不足异常的问题。

当我检查生成的查询时

SELECT [t0].[Id], [t0].[CreatedBy], [t0].[CreatedDate], [t0].[ModifiedBy], 
[t0].[ModifiedDate], [t0].[IsDeleted], [t0].[UntileTime], [t0].[Desktop], 
[t0].[Laptop], [t0].[Title], [t0].[Responsive], [t0].[Mobile], [t0].[ActiveTime],
[t0].[Tablet]
FROM [Countent_FreeArea] AS [t0]

似乎 Linq-to-SQL 正在从数据库中获取所有数据并在内存中对其进行过滤。

public class Context
{
    private DataContext daynamicContext;
    public DataContext DaynamicContext
    {
        get
        {
            if (daynamicContext == null)
            {
                System.Configuration.ConnectionStringSettingsCollection connectionStrings = WebConfigurationManager.ConnectionStrings;
                daynamicContext = new DataContext(connectionStrings["connectionStrings"].ToString());
            }
            return daynamicContext;
        }
    }
}

【问题讨论】:

  • 嗯,.GetTable() 方法在我看来是一个调用 get the entire table 这正是你所看到的.....
  • GetTable() 方法返回不调用get的“ITable”。我试图删除查询行并保留 Just GetTable() 结果不会生成查询
  • 你能告诉我们DaynamicContext是什么吗??
  • 我编辑问题以显示 daynamicContext 并且 tbl 对象是运行时生成的类

标签: c# linq dynamic linq-to-sql


【解决方案1】:

GetTable 方法将首先获取整个表,然后从列表中选择第一个值。也不要使用Take(),而是使用FirstOrDefault()

【讨论】:

  • GetTable() 方法返回不调用get的“ITable”。我试图删除查询行并保留 Just GetTable() 结果不会生成查询
  • 试过删除 Take 吗?另外,您为什么要将其转换为可枚举然后转换为列表?
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多