2

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

yash fale
  • 235
  • 1
  • 4
  • 19
  • 1
    `SCOPE_IDENTITY()` does not generate id values, it simply returns the last identity value generated in the current scope. It's also not your best option. Since you are inserting multiple data tables, your best option would probably be [this.](http://stackoverflow.com/a/34832231/3094533) – Zohar Peled Dec 17 '16 at 13:16
  • i have posted code i got parent id from db using scope identity but when i try to get in child using data Relation it fails , do i missing something here – yash fale Dec 19 '16 at 13:22
  • I would use a stored procedure instead of round trips between sql server and c#. not only it will be easier to write and maintain, it will probably have better performance. – Zohar Peled Dec 27 '16 at 07:30
  • What is the pk for the InnBoundTable? – boggy Dec 27 '16 at 07:31
  • for [InnBoundTable] table column [Id] is foreign key and [InnId] is a primary key – yash fale Dec 27 '16 at 07:37

0 Answers0