简体   繁体   English

如何为要与dataTable插入的一对多关系表编写插入语句

[英]how to write insert statements for one to many relationships tables to insert with dataTable

i have 3 tables in dataset when i click save button, i want to add these tables to database tables using data adapter all these 3 tables primary keys are sql generated auto number. 当我单击保存按钮时,我在数据集中有3个表,我想使用数据适配器将这些表添加到数据库表中,所有这3个表的主键都是sql生成的自动编号。

relation ships Invoice, InvoiceProduct , InvoiceProductExp tables are: InvoiceNo has many InvoiceProductNo InvoiceProductNo has many InvoiceProductExpNo 关系船舶Invoice,InvoiceProduct和InvoiceProductExp表是:InvoiceNo有很多InvoiceProductNo InvoiceProductNo有很多InvoiceProductExpNo

the following code can not solve these relaionship 以下代码无法解决这些关系

DECLARE @InvoiceNo INT
DECLARE @InvoiceProductNo INT
INSERT INTO Invoice ([Date])
VALUES (GETDATE())
SELECT @InvoiceNo = SCOPE_IDENTITY()
INSERT INTO InvoiceProduct([InvoiceNo])
VALUES (@InvoiceNo)
SELECT @InvoiceProductNo = SCOPE_IDENTITY() 
INSERT INTO InvoiceProductExp ([InvoiceProductNo], [InvoiceNo])
VALUES (@InvoiceProductNo, @InvoiceNo)

If you are using a Dataset and DataAdapter, you shouldn't be issuing all those statements. 如果使用的是Dataset和DataAdapter,则不应发出所有这些语句。 Each data adapter needs only know how to update its records. 每个数据适配器仅需要知道如何更新其记录。 When you update the parent, the identity value will be put into your dataset automatically and the child records will automatically be set (assuming you set up your relationships correctly.) After that, you update the child tables. 当您更新父表时,标识值将自动添加到数据集中,并且子记录将自动设置(假设您正确设置了关系。)之后,您将更新子表。

Read some of the comments in this SO thread, there are some good code snippets there. 阅读 SO线程中的一些注释,那里有一些不错的代码片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 Entity Framework Core 试图将记录从多对多关系而不是连接表插入到其中一个表中? - Why is Entity Framework Core attempting to insert records into one of the tables from many to many relationships and NOT the join table? 将数据插入数据库中具有一对多关系的两个表中 ASP.NET EF - Insert data into two tables in database with one to many relationships ASP.NET EF 插入没有关系的两个表 - Insert into two tables with no relationships 使用Linq查询和SQLite插入多个表(一对一关系) - Insert into multiple tables (one to one relationships) with Linq queries and SQLite 将批量数据插入到具有一对多关系的表中 - Insert bulk data into tables that are in a one to many relationship 如何插入具有多对多关系表的记录 - How to insert record with many to many relational tables 如何使用LINQ to SQL将数据插入具有关系的4个表中 - How to insert data into 4 tables that have relationships using LINQ to sql 通过循环数据表C#创建插入语句 - Create Insert Statements by looping Datatable C# 插入具有一对多关系的新实体,而不在两个表中都创建记录 - Insert new Entity with one to many relationship not creating records in both tables 如何使用实体框架在WPF c#中的两个表之间插​​入一对多关系的数据? - How to insert data for one to many relationship between two tables in WPF c# using Entity Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM