Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

c# - Dataset from database is empty

I'm accessing a table from my database. I have added the tables as a dataset in Visual Studio 2013, but when I try to use it, it comes out empty.

This is what I'm trying to do:

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

I found out that orders was empty, so I added

Console.WriteLine(context.Orders.Count);

which gave me an output of 0. What went wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found out that I needed to fill my dataset with data, or it would stay empty.

A SqlDataAdapter did the trick:

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

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

There are several overloaded methods for SqlDataAdapter.Fill, of which one takes a dataset and another takes a datatable. When I first used the SqlDataAdapter, I used the one that takes a dataset

adapter.Fill(context);

which still gave me an empty context.Orders. The correct one takes a datatable:

adapter.Fill(context.Orders);

This one worked and returned the dates as expected.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...