DataSetオブジェクトをインスタンス化すると、CRUD操作用のSQLサービスベースのデータベースへの接続が自動的に作成されますか?

fgharo91

これが私がしたすべてです:

  1. Visual Studio 2013 C#プロジェクトで、サービスデータベース(.mdfファイル)を作成しました。注:名前をDatabase1.mdfからfghLocalDB.mdfに変更しました。ここに画像の説明を入力してください

  2. このデータベースをサーバーエクスプローラーで開きました。

  3. テーブルデザイナーを使用して、CountryとCarbonDioxideという2つのテーブルを作成しました。 ここに画像の説明を入力してください

  4. CountryテーブルのDataTableに示されているように、Countryテーブルにエントリを追加しました。 ここに画像の説明を入力してください

  5. I did the following to create a DataSet my application can use. I created a Data Source by clicking on the "Project" option on the top menu bar and clicking on the "Add New Data Source ..." option from the drop down. ここに画像の説明を入力してください ここに画像の説明を入力してください ここに画像の説明を入力してください ここに画像の説明を入力してください

  6. This is what my project files looked like at this point. ここに画像の説明を入力してください

  7. I wrote the following code in the main method thinking that this would be all I need to write to the database.

    // Create a connection to the DataSet and TableAdapters that will communicate with our 
    // local database to handle CRUD operations.
    
    
    fghLocalDBDataSet dataSet = new fghLocalDBDataSet();
    fghLocalDBDataSetTableAdapters.CountryTableAdapter countryTableAdapter = 
    new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
    
    try
    {
       // Insert a row into Country table. EDIT 1 Will comment after first program run.
       Console.WriteLine(countryTableAdapter.Insert("United States"));
    
       // Actually writeback information to the database?      
       // dataSet.AcceptChanges(); EDIT 2 commented this as LeY suggested it was not needed.
    
    
       // EDIT 3 Validation code as suggested by Ley.
       var dt = new fghLocalDBDataSet.CountryDataTable();
       var adapter = new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
       adapter.Fill(dt);
    
       foreach (var row in dt)
       {
                // This does not get executed after a second run of the program.        
                // Nothing is printed to the screen.
                Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
       }
       Console.Read();
    }
    catch(SqlException exception){
       Console.WriteLine("ERROR: " + exception.ToString());
    }
    Console.ReadLine();
    
  8. I ran the program and everything seemed fine.

  9. I opened the tables by right clicking on these tables in the server explorer and pressing "Show Data Table".
  10. The "United States" row was not added as wanted.
  11. I think it has to do with the connectionstring. I right clicked on my project and opened properties. ここに画像の説明を入力してください ここに画像の説明を入力してください

  12. Here I made sure the connection string matched that of the local database by looking at the string in the properties of the database. They are the same. ここに画像の説明を入力してください

I copied and pasted the actual text for each connection string:

Connection string of project:

Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True

Connection string of actual database (.mdf file):

Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True

I am assuming |DataDirectory| is equal to C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf; since in the picture above when I clicked on the button to expand the Value of the connection string the connection properties window opened up and had this path for the database file name.

My question in a nutshell is does instantiating a DataSet object in the code automatically create a connection to a SQL service-based database for CRUD operations?

If not how do I connect my DataSet object to my sql database so that way I can actually write to the database when using the TableAdapters?

I read the following links:

Insert method of TableAdapter not working?

TableAdapter Insert not persisting data

Use connectionstring from web.config in source code file

Do I need an actual SqlConnection object? and how to I connect this to the DataSet & TableAdapters?

LeY

I never used tableadpter.insert() method. But I tried it on my local machine, and it works. I can't figure out your problem based on the information you provided, sorry, but I can point you a direction.

If you created everything from wizard, you don't need to worry about the connection, the table Adapters will handle the connection for you. The connection string (you circled) will be added to your app.config file as well as your setting class automaticly. That is how your application (or you) uses it.

var countryTableAdapter = new CountryTableAdapter(); countryTableAdapter.Insert("United States");

This 2 lines of code are enough to insert the row into database if there is no exception thrown, I don't know why it doesn't work for you. Maybe the way you verify it somehow goes wrong, but you can verify it in another way.

The countryTableAdapter.Insert method will return the number of row get affected, in your case , should be one. So put the following code in , and set a breakpoint after it. if the rowAffected == 1, then the insertion works.

var rowAffected = countryTableAdapter.Insert("Test2")

If you need more confirmation , try this.

var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new CountryTableAdapter();
adapter.fill(dt);
foreach (var row in dt){
    Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();

you will see all the records in your table. I hope this will help.

By the way, from your code

dataSet.AcceptChanges();

The line of code above doesn't update the database at all. It only modify your local data storage. it overwrites your dataRow original version using current version and change the current version row state to unchanged.

Only the tableadapters can talk to database (not true I know, but I just want to make a point that Dataset can not talk to database directly). And I usually only need tableadapte.Update method and pass the dataSet or dataTable in with correct RowState.

tableAdapter.updateメソッドは、データベースが正常に更新された場合、最終的に各行でAcceptChangesを呼び出します。

メモリ内のデータセットのみを更新する場合を除いて、AcceptChangesを明示的に呼び出す必要はありません。

DataSetとTableAdapterがどのように機能するかを全体的に把握するには、ADO.NETアーキテクチャを読むことをお勧めします

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관