根据MSDN 文档,在 foreach 循环中迭代之前不会执行 LINQ 查询。
但是当我尝试以下操作时:
namespace MCSD487_AdoConnection
{
class Program
{
static void Main(string[] args)
{
DataSet dataSet = new DataSet();
dataSet.Locale = CultureInfo.InvariantCulture;
FillDataSet(dataSet);
DataTable folders = dataSet.Tables["Folder"];
IEnumerable<DataRow> folderQuery = folders.AsEnumerable();
IEnumerable<DataRow> aFolders = folderQuery.Where(f => f.Field<string>("Name")[0].ToString().ToLower() == "a");
// this is where I thought the SQL execution whould happen
foreach (DataRow row in aFolders)
{
Console.WriteLine("{0} was created on {1}", row.Field<string>("Name"), row.Field<DateTime>("DateTime"));
}
Console.ReadLine();
}
internal static void FillDataSet(DataSet dataSet)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT DateTime, Name FROM Folder", connectionString);
// Add table mappings.
dataAdapter.TableMappings.Add("Table", "Folder");
dataAdapter.Fill(dataSet);
// Fill the DataSet.
// This it where the actual SQL executes
dataAdapter.Fill(dataSet);
}
catch (SqlException ex)
{
Console.WriteLine("SQL exception occurred: " + ex.Message);
}
}
}
}
我查看了我的 SQL Server Profiler,我可以看到实际的 SQL 调用是在我调用dataAdapter.Fill(dataSet)
FillDataSet 方法时执行的,而不是在遍历行时执行的。
我的问题是:如何让 LINQ 只对以“a”开头的名称执行 SQL 执行(而不在 FillDataSet 方法的 SQL commandText 中指定)?
编辑 2013-07-07 23:44:根据 Evan Harpers 的回答,我以以下解决方案结束:
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace MCSD487_AdoConnection
{
[Table(Name = "Folder")]
public class Folder
{
private int _Id;
[Column(IsPrimaryKey = true, Storage = "_Id")]
public int Id
{
get { return _Id; }
set { _Id = value; }
}
private DateTime _DateTime;
[Column(Storage = "_DateTime")]
public DateTime DateTime
{
get { return _DateTime; }
set { _DateTime = value; }
}
private string _Name;
[Column(Storage = "_Name")]
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
class Program
{
static void Main(string[] args)
{
DataContext db = new DataContext(new SqlConnection(@"Data Source=OLF\OLF;Initial Catalog=DirStructure;Integrated Security=True"));
Table<Folder> folders = db.GetTable<Folder>();
IQueryable<Folder> folderQuery = from folder in folders
where folder.Name[0].ToString().ToLower() == "a"
select folder;
foreach (Folder folder in folderQuery)
{
Console.WriteLine("{0} was created on {1}", folder.Name, folder.DateTime);
}
Console.ReadLine();
}
}
}
谢谢你指引我正确的方向。