How to update Dataset Parent & Child tables with Autogenerated Identity Key?

后端 未结 3 725
北海茫月
北海茫月 2020-12-10 18:03

I am using ADO.NET Datasets in my VB Applications. I have a typed dataset with one Parent table and many child tables. I want to generate Identity Key when I insert data int

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 18:20

    Couple of things to point out.

    1. Yes, you definitely need relations assigned for both tables. You can check from xsd editor (double click your xsd file). By default the relation is set as 'relation only' which doesn't has any 'update rule'. Edit this relation by going into 'edit relation' and select 'Foreign Key Constraint Only' or 'Both~~~' one. And need to set 'Update Rule' as Cascade! 'Delete Rule' is up to you.

    2. Now when you use a new parent table row's ID (AutoIncrement) for new child table rows as a foreign key, You have to add the parent row into the table first before you use the new parent row's ID around.

    3. As soon as you call Update for the parent table using tableadapter, the associated child table's new rows will have correct parentID AUTOMATICALLY.

    My simple code snippets:

    '--- Make Parent Row
    Dim drOrder as TOrderRow = myDS.TOder.NewTOrderRow
    drOrder.SomeValue = "SomeValue"
    myDS.TOrder.AddTOrderRow(drOrder) '===> THIS SHOULD BE DONE BEFORE CHILD ROWS
    
    '--- Now Add Child Rows!!! there are multiple ways to add a row into tables....
    myDS.TOrderDetail.AddTOrderDetailRow(drOrder, "detailValue1")
    myDS.TOrderDetail.AddTOrderDetailRow(drOrder, "detailvalue2")
    '....
    '....
    
    '--- Update Parent table first
    myTableAdapterTOrder.Update(myDS.TOrder)
    '--- As soon as you run this Update above for parent, the new parent row's AutoID(-1)
    '--- will become real number given by SQL server. And also new rows in child table will
    '--- have the updated parentID
    
    '--- Now update child table
    myTableAdapterTOrderDetail.Update(myDS.TOrderDetail)
    

    I hope it helps!

提交回复
热议问题