我在 C# (.NET 3.5) 中使用带有强类型数据集的 ADO.NET。我想向两个以 1:n 关系相关的表插入一个新行。
Attachments
表保存关系的主键部分,LicenseAttachments
表保存外键部分。
AttachmentsDataSet.InvoiceRow invoice; // Set to a valid row, also referenced in InvoiceAttachments
AttachmentsDataSet.AttachmentsRow attachment;
attachment = attachmentsDataSet.Attachments.AddAttachmentsRow("Name", "Description");
attachmentsDataSet.InvoiceAttachments.AddInvoiceAttachmentsRow(invoice, attachment);
当然,当我第一次更新 InvoicesAttachments
表时,我会从 SQL Server 得到一个外键违规,所以我尝试先更新 Attachments
表,这将创建行,但会删除 InvoiceAttachments
表中的附件关联。为什么?
我该如何解决这个问题?
最佳答案
在表之间的关系上,确保选择“关系和外键约束”并且“更新规则”设置为“级联”。结合适配器上的“刷新数据表”选项,在插入父行后,更新后的 ID 将“级联”关系,防止数据集中的外键违规。然后您的子表将准备好正确插入数据库。
关于c# - 使用强类型数据集在关系中插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1328092/