Linq to Sql转义WHERE子句

时间:2015-06-13 07:25:05

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

我有这个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。

enter image description here

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

当我检查生成的查询时

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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

GetTable方法将首先获取整个表,然后从列表中选择第一个值。此外,请使用Take()

,而不是使用FirstOrDefault()