从数据库查询数据时

时间:2013-07-07 19:10:42

标签: c# linq ado.net

根据MSDN documentation,在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,我可以看到当我在FillDataSet方法中调用dataAdapter.Fill(dataSet)而不是在遍历行时调用实际的SQL调用。

我的问题是:如何让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();
        }
    }
}

感谢指导我朝着正确的方向前进。

2 个答案:

答案 0 :(得分:3)

这正是预期的行为。您正在使用ADO.NET将数据导入DataTable,然后根据ADO.NET的disconnected architecture查询DataTable而不是基础数据库。

如果您希望及时将LINQ查询转换为优化的数据库调用,请使用LINQ to SQL之类的内容。

答案 1 :(得分:0)

使用DataSet你无法做到。唯一的方法是使用有限的结果填充DataSet / Table适配器(必须用SQL编写内容的开头)。