我有兩個帶外鍵的表,第一個是:
tblFile : 檔案 ID、檔案名...
第二個是:
tblChild(在 Datagridview 中):ChildID、ChildName、ChildBirthDate、fkFileID。
單擊保存按鈕(在表單中)時,如果行(添加或編輯或洗掉),如何更新第二個表中的所有行?(表格例如:
創建一個新專案,添加一個 DataSet 型別的檔案并打開它。右鍵單擊表面,添加一個表配接器

配置連接字串等,從陳述句中選擇添加

放置一個按主鍵拉取的查詢

將“ByFileId”添加到查詢名稱

完成,并重命名生成的資料表以洗掉“tbl”

對另一個表重復該程序。你也應該看到關系出現

這是您的資料訪問部分排序。如果您愿意,您可以查看 VS 在 DataSetX.Designer.cs 中為您撰寫的大量引數化 SQL 代碼。

在設計器模式下打開一個新表單,并顯示資料源視窗(查看選單,其他視窗 - 希望您使用的是 .net 框架):

資料源中有兩個子節點,因為一個是頂層,一個與檔案相關;我們將使用檔案一,因為它將演示加載和保存相關資料
將以下節點拖到表單上:

I'm not trying to win any beauty contests here; just demoing a concept. Tarting it up can come later
That's it; everything needed to load update and save data has been done. You're right; i didn't write a single line of code
Let's put some dummy data into the db:

And, before we load the app, I'll just tweak a property on the tableadapter that will make it easier to load lots of data (because the only queries in the dataset at the moment can only load one record at once). Turn off ClearBeforeFill in both tableAdapters (in the tray under the form)

Run the app. I loaded all the data available in my db by entering 1 in the box, clicking Fill, changing to 2, Fill, then in the child box 1, fill, 2, fill, 3, fill - remember this is just a demo; all this can be done programmatically, and with different queries that select by name etc (tableadapters can have multiple queries)

You can click the nav at the top to switch the file between 1 and 2 and note the related records in the grid updates automatically:

you can edit anything you see and hit save

And it's in the DB and done..

If you'd added decords or deleted records, those changes would be saved too, by Update() - it doesn't just call UPDATE queries, despite being called Update()
It's not magic, by the way; you can find all the code that did it in the .Designer files and the form codebehind.. it's just that it's all code that VS can do a better job of writing than we can so leave VS to do it, and just use the code it wrote for you
So how do we make these things useful? Querying by PK is all well and good but you don't ask a user to type PKs.. You can add more queries to your tableadapters that do other stuff:


Having added these queries to your adapters you could ask your user for a filename, then run a code like:
fileTableAdapter.FillByName(someDataset.File, filenametextbox.Text);
foreach(var f in someDataset.File){
childTableAdapter.FillByFileId(someDataset.Child, f.FileId);
}
That will pull a file(s) by name (the user can type % into the filename textboxfor a wildcard) and then, for each file record, pull all the related child records..
The tables in the stringly typed dataset are also nicer to query via LINQ:
someDataset.File.Where(f => f.FileId == "hello");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/336529.html
標籤:C# sql-server
上一篇:為什么腳手架生成的控制器在將其DbContext的DbSet屬性傳遞到視圖之前將其轉換為List?
下一篇:以引導程式形式根據條件使文本變灰
