1

我正在使用带有 MSSQL 后端的 c# 数据集。我有一个引用自身的表。当我添加一个父行然后添加一个子行时,没有在两者之间调用更新,我得到一个约束异常。我认为这是因为插入的执行顺序与添加实体的顺序不同。有没有办法解决这个问题?我希望用户能够添加项目,然后在最后提交到数据库(当他们确认一切正确时)。

这是我的表定义和示例应用程序:

CREATE TABLE [dbo].[AssetServiceItems] (
    [ServiceItemID] [int] IDENTITY(1, 1) NOT NULL,
    [Description] [nvarchar](50) NOT NULL,
    [Parent] [int] NULL,
    CONSTRAINT [PK_AssetServiceItems] PRIMARY KEY CLUSTERED ([ServiceItemID] ASC) WITH (
        PAD_INDEX = OFF,
        STATISTICS_NORECOMPUTE = OFF,
        IGNORE_DUP_KEY = OFF,
        ALLOW_ROW_LOCKS = ON,
        ALLOW_PAGE_LOCKS = ON
        ) ON [PRIMARY]
    ) ON [PRIMARY]

ALTER TABLE [dbo].[AssetServiceItems]
    WITH CHECK ADD CONSTRAINT [AssetServiceItems_parent] FOREIGN KEY ([Parent]) REFERENCES [dbo].[AssetServiceItems]([ServiceItemID])

ALTER TABLE [dbo].[AssetServiceItems] CHECK CONSTRAINT [AssetServiceItems_parent]

和程序...

public static void Main(string[] args)
{

  RelTestTableAdapters.AssetServiceItemsTableAdapter adapter = new RelTestTableAdapters.AssetServiceItemsTableAdapter();
  RelTest dataSet = new RelTest();

  var parent =  dataSet.AssetServiceItems.NewAssetServiceItemsRow();
  parent.Description = "Parent";
  dataSet.AssetServiceItems.AddAssetServiceItemsRow(parent);

  var child = dataSet.AssetServiceItems.NewAssetServiceItemsRow();
  child.Description = "child";
  child.SetParentRow(parent);
  dataSet.AssetServiceItems.AddAssetServiceItemsRow(child);

  adapter.Update(dataSet);

    Console.ReadKey(true);
}

INSERT 语句与 FOREIGN KEY SAME TABLE 约束“AssetServiceItems_parent”冲突。冲突发生在数据库“RelTest”、表“dbo.AssetServiceItems”、列“ServiceItemID”中。

4

0 回答 0