来自数据库的数据集为空

Dataset from database is empty

我正在从我的数据库访问 table。我在 Visual Studio 2013 中添加了 tables 作为数据集,但是当我尝试使用它时,它是空的。

这就是我想要做的:

IQueryable<NorthwindDataSet.OrdersRow> LookupOrdersForYear(int year)
{
    using (var context = new NorthwindDataSet())
    {
        var orders =
            from order in context.Orders
            where order.OrderDate != null && order.OrderDate.Year >= year
            select order;
        return orders.ToList().AsQueryable();
    }
}

我发现orders是空的,所以我添加了

Console.WriteLine(context.Orders.Count);

这给了我 0 的输出。出了什么问题?

我发现我需要用数据填充我的数据集,否则它将保持为空。

SqlDataAdapter 成功了:

SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand("SELECT * FROM Orders");
string connString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);

adapter.SelectCommand = command;
adapter.SelectCommand.Connection = conn;
adapter.Fill(context.Orders);

SqlDataAdapter.Fill有几个重载方法,一个取数据集,一个取数据表。当我第一次使用 SqlDataAdapter 时,我使用的是带数据集的那个

adapter.Fill(context);

这仍然给了我一个空 context.Orders。正确的取数据表:

adapter.Fill(context.Orders);

这个有效并返回了预期的日期。