Why do I get empty results using generated code from DB?

浪子不回头ぞ 提交于 2020-01-06 13:08:32

问题


I'm using SQL Server 2005. I have a table scores with 6 rows and columns - name, score and id.

I added the data source with VS and it generated a dataset called testDataSet.

So I tried the following code which gives me zero results:

testDataSet db = new testDataSet();

var result = from row in db.scores
             select row.name;

Where is the problem?


回答1:


The probem you are having is that you are querying an empty DataSet.

You first have to create a connection to your testDataSet and fill the tables contained in it with data from your database.

If you have created testDataSet with the automated tools VS provides then the tool will have also created the relevant TableDataAdapters (in their own namespace) to fill and update your DataSet.

Initialize the relevant TableDataAdapter and fetch the data from the database with the Fill(db) method.




回答2:


you sould query dataTable like this:

DataTable products = ds.Tables["Product"];

var query = products.AsEnumerable().
Select(product => new
{
    ProductName = product.Field<string>("Name"),
    ProductNumber = product.Field<string>("ProductNumber"),
    Price = product.Field<decimal>("ListPrice")
});



回答3:


Try this code instead:

scoresTableAdapter adapter = new scoresTableAdapter();
var result = from row in adapter.GetData() select row.name;

Others are right that your problem is that you are not querying the data. When you generated the dataset, an adapter is also generated for you, that will help you to query the data as shown above.




回答4:


The DataSet is just a structured container for the query results, it has no connection to the data source (database). In order to populate the DataSet with data you need to use a DataAdapter with a SelectCommand and call the Fill method.

var myConn = new SqlConnection ("..." );
var myAdapter = new SqlDataAdapter ( "SELECT * FROM TableName", myConn );
var myData = new testDataSet( );
myAdapter.Fill ( myData, "TableName" );


来源:https://stackoverflow.com/questions/6329781/why-do-i-get-empty-results-using-generated-code-from-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!