Insert ParentTable Id into child table using Scope_identity by using adapter in C#

864 views Asked by At

I have a parent table ParentTable which has a primary key. I want to insert data into ParentTable and then use that primary key to insert rows into the child table ChildTable.

Example

ParentTable:

Id    ClassName
----------------
1     MailClass
2     HelperClass
3     DataClass   

ChildTable:

ChildId  Id         Details
---------------------------
200      1          this is for Main Class
201      1          this is for Main Class
203      2          this is for Helper Class

So if id = 3 is added to ParentTable, I want to insert a row with that id = 3 into the ChildTable and so on...

Here I have two DataTables - dtParentTable and dtChild. ParentTable id must be generated with scope_identity and this id must be inserted into child table

We have to use adapter.Update(); to achieve this

Trying to use this : https://msdn.microsoft.com/en-us/library/ks9f57t0(v=vs.110).aspx

Code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace checkScopIdentity
{
    class Program
    {
        static void Main(string[] args)
        {

            string strConn1 = "Data Source=CS40-PC;Initial Catalog=DBName;User ID=sa;Password=root";

            using (SqlConnection conn = new SqlConnection(strConn1))
            {
 conn.Open();

                SqlDataAdapter adapter = new SqlDataAdapter("SELECT Id, InterfaceName FROM ParenTable",conn);


                adapter.InsertCommand = new SqlCommand(
                    "INSERT INTO ParenTable (InterfaceName) " +
                    "VALUES (@InterfaceName); " +
                    "SELECT Id, InterfaceName FROM ParenTable " +
                    "WHERE Id = SCOPE_IDENTITY();", conn);

                adapter.InsertCommand.Parameters.Add(
                   new SqlParameter("@InterfaceName", SqlDbType.NVarChar, 40,
                   "InterfaceName"));
                adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.Both;


                adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                DataTable ParenTableFinal = new DataTable();
                adapter.Fill(ParenTableFinal);


                DataRow newRow = ParenTableFinal.NewRow();
                newRow["InterfaceName"] = "New Shipper"; 
                ParenTableFinal.Rows.Add(newRow);

                DataTable dataChanges = new DataTable();
                    dataChanges = ParenTableFinal.GetChanges();

                adapter.RowUpdated +=  new SqlRowUpdatedEventHandler(OnRowUpdated);

               adapter.Update(dataChanges);


                // second Table 
                DataSet ds = new DataSet();
                DataTable dtInbound = new DataTable();
                SqlDataAdapter adapterChild = new SqlDataAdapter("SELECT Id,InnId,Name,Contact FROM InnBoundTable", conn);

                adapterChild.FillSchema(dtInbound, SchemaType.Source);
                dtInbound.Rows.Add(null,null,"Yash","Fale");
                dtInbound.GetChanges();


                ds.Tables.Add(dataChanges);
                ds.Tables.Add(dtInbound);

                ds.EnforceConstraints = false;
                DataRelation dRelation ;

                dRelation = ds.Relations.Add("info", ds.Tables["ParenTable"].Columns["Id"], ds.Tables["InnBoundTable"].Columns["Id"]);

                dRelation.ChildKeyConstraint.UpdateRule = Rule.Cascade;


                ds.AcceptChanges();
                ds.GetChanges();

                Console.WriteLine("Rows after merge.");
                foreach (DataRow row in dtInbound.Rows)
                {
                    {
                        Console.WriteLine("{0}: {1}", row[0], row[1]);
                    }
                }

                conn.Close();
            }

            Console.ReadKey();

        }

        private static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                e.Status = UpdateStatus.SkipCurrentRow;
            }
        }
    }
}

//ParenTable

CREATE TABLE [dbo].[ParenTable](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [InterfaceName] [nvarchar](50) NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[InnBoundTable](
    [Id] [int] NULL,
    [InnId] [int] NULL,
    [Name] [nchar](10) NULL,
    [Contact] [nchar](10) NULL
) ON [PRIMARY]

Here trying to get parentTable Id In "InnBoundTable" but not reflecting any changes , showing empty values in Id for InnBoundTable i.e childTable

enter image description here

0

There are 0 answers