C# 使用C中的适配器,使用Scope_标识将ParentTable Id插入子表#

C# 使用C中的适配器,使用Scope_标识将ParentTable Id插入子表#,c#,sql-server,dataadapter,C#,Sql Server,Dataadapter,我有一个父表ParentTable,它有一个主键。我想将数据插入父表ParentTable,然后使用该主键将行插入子表ChildTable 范例 父表: Id ClassName ---------------- 1 MailClass 2 HelperClass 3 DataClass ChildId Id Details --------------------------- 200 1 this is fo

我有一个父表
ParentTable
,它有一个主键。我想将数据插入父表
ParentTable
,然后使用该主键将行插入子表
ChildTable

范例

父表

Id    ClassName
----------------
1     MailClass
2     HelperClass
3     DataClass   
ChildId  Id         Details
---------------------------
200      1          this is for Main Class
201      1          this is for Main Class
203      2          this is for Helper Class
子表

Id    ClassName
----------------
1     MailClass
2     HelperClass
3     DataClass   
ChildId  Id         Details
---------------------------
200      1          this is for Main Class
201      1          this is for Main Class
203      2          this is for Helper Class
因此,如果将
id=3
添加到
ParentTable
,我想在
ChildTable
中插入一行id=3,以此类推

这里我有两个
DataTable
s-
dtParentTable
dtChild
ParentTable
id必须使用
scope\u identity
生成,并且该id必须插入到子表中

我们必须使用
adapter.Update()以实现此目的

尝试使用此选项:

代码:

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;
            }
        }
    }
}
//父母的

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]
这里尝试在“InnBoundTable”中获取parentTable Id,但不反映任何更改,在InnBoundTable的Id中显示空值,即childTable


SCOPE\u IDENTITY()
不生成id值,它只返回在当前作用域中生成的最后一个标识值。这也不是你最好的选择。由于要插入多个数据表,最好的选择可能是我发布了代码,我使用范围标识从db获得了父id,但当我尝试使用数据关系进入子对象时失败了,我是否遗漏了一些内容?我将使用存储过程,而不是sql server和c#之间的往返。它不仅更易于编写和维护,而且可能具有更好的性能。InnBoundTable的主键是什么?对于[InnBoundTable],表列[Id]是外键,[InnId]是主键