升级数据层应用程序时违反PRIMARY KEY约束错误

时间:2017-10-06 10:44:26

标签: sql-server composite-primary-key composite-key dacpac data-tier-applications

我正在尝试使用数据层应用程序来标准化我的数据库架构。

为此,我有一个现有的数据层应用程序,我想将其应用于我的数据库。

在尝试升级Data-Tier应用程序时,收到以下错误消息:

Error SQL72014: .Net SqlClient Data Provider: Msg 2627, Level 14, State 1, Line 19 Violation of PRIMARY KEY constraint 'tmp_ms_xx_constraint_PK_ResidencyAgent'. Cannot insert duplicate key in object 'dbo.tmp_ms_xx_ResidencyAgent'. The duplicate key value is (1).
Error SQL72045: Script execution error.  The executed script:
BEGIN TRANSACTION;

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

CREATE TABLE [dbo].[tmp_ms_xx_ResidencyAgent] (
    [ResidenceID] INT      NOT NULL,
    [AgentID]     INT      NOT NULL,
    [CreateDate]  DATETIME NOT NULL,
    [IsDefault]   BIT      NULL,
    CONSTRAINT [tmp_ms_xx_constraint_PK_ResidencyAgent] PRIMARY KEY CLUSTERED ([AgentID] ASC)
);

IF EXISTS (SELECT TOP 1 1 FROM   [dbo].[ResidencyAgent])
    BEGIN

        INSERT INTO [dbo].[tmp_ms_xx_ResidencyAgent] ([AgentID], [ResidenceID], [IsDefault], [CreateDate])
        SELECT   [AgentID],
                 [ResidenceID],
                 [IsDefault],
                 [CreateDate]
        FROM     [dbo].[ResidencyAgent]
        ORDER BY [AgentID] ASC;

    END

DROP TABLE [dbo].[ResidencyAgent];

EXECUTE sp_rename N'[dbo].[tmp_ms_xx_ResidencyAgent]', N'ResidencyAgent';

EXECUTE sp_rename N'[dbo].[tmp_ms_xx_constraint_PK_ResidencyAgent]', N'PK_ResidencyAgent'

我已尝试对数据库运行此查询,错误消息为

Msg 2627, Level 14, State 1, Line 19
Violation of PRIMARY KEY constraint 'tmp_ms_xx_constraint_PK_ResidencyAgent'. Cannot insert duplicate key in object 'dbo.tmp_ms_xx_ResidencyAgent'. The duplicate key value is (1).

[dbo]。[ResidencyAgent]表中当前的数据是:

+-----------+-------------+-----------+-------------------------+
| AgentID   | ResidenceID | IsDefault | CreateDate              |
+-----------+-------------+-----------+-------------------------+
| 1         | 1           | 1         | 2011-10-06 13:28:42.110 |
| 1         | 2           | 0         | 2011-10-06 13:28:43.483 |
| 1         | 28          | 0         | 2017-09-01 14:53:08.750 |
| 6         | 1           | 1         | 2016-02-10 14:21:57.150 |
| 14        | 1           | 1         | 2017-08-07 16:37:13.020 |
+-----------+-------------+-----------+-------------------------+

数据层应用程序执行脚本时出现问题的原因是因为该表包含复合键,因此它创建的临时表应定义如下:

CREATE TABLE [dbo].[tmp_ms_xx_ResidencyAgent](
    [ResidenceID] [int] NOT NULL,
    [AgentID] [int] NOT NULL,
    [IsDefault] [bit] NULL,
    [CreateDate] [datetime] NOT NULL,
 CONSTRAINT [tmp_ms_xx_PK_ResidencyAgent] PRIMARY KEY CLUSTERED 
(
    [ResidenceID] ASC,
    [AgentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

还有其他人遇到过类似的东西吗?如果是这样,他们是如何解决的?

我是否可以通过某种方式使数据层应用程序能够识别'这个 - 我可以设置一个选项吗?我可以编辑用于升级数据层应用程序的dacpac以解决此问题吗?

谢谢,

肖恩

0 个答案:

没有答案