运行我的create + seed数据库脚本时发生错误。
无法在具有唯一索引'IX_UniqueResCatName'的对象'dbo.ResourceCategories'中插入重复的键行。重复的键值为(DSC20,DST20)。
它发生在我尝试播种的第一行,但是数据库肯定已被删除并销毁。
我的ResouceCategory.cs
文件已设置为具有2个元素的唯一索引,如here
[MinLength(1), MaxLength(5)]
[Index("IX_UniqueResCatName", 1, IsUnique = true)]
public string Name { get; set; }
[MaxLength(50)]
[Index("IX_UniqueResCatName", 2, IsUnique = true)]
public string Description { get; set; }
我已经为此自动生成了迁移(在播种之前运行),相关部分看起来像
CREATE UNIQUE INDEX [IX_UniqueResCatName]
ON [dbo].[ResourceCategories] ([Name], [Description])
还有摘录的SQL摘录(自动从bash脚本运行):
INSERT INTO [dbo].[ResourceCategories] ([Id], [Description], [Name], [IsActive], [CreatedByUser], [CreatedOn], [LastUpdatedByUser], [LastUpdatedOn])
VALUES (NEWID(), 'DST20', 'DSC20', 1, 'system', GETDATE(), 'system', GETDATE())
INSERT INTO [dbo].[ResourceCategories] ([Id], [Description], [Name], [IsActive],[CreatedByUser], [CreatedOn], [LastUpdatedByUser], [LastUpdatedOn])
VALUES (NEWID(), 'EPT10', 'EPC10', 1, 'system', GETDATE(), 'system', GETDATE())
INSERT INTO [dbo].[ResourceCategories] ([Id], [Description], [Name], [IsActive],[CreatedByUser], [CreatedOn], [LastUpdatedByUser], [LastUpdatedOn])
VALUES (NEWID(), 'EPT10', 'EPC11', 1, 'system', GETDATE(), 'system', GETDATE())
INSERT INTO [dbo].[ResourceCategories] ([Id], [Description], [Name], [IsActive], [CreatedByUser], [CreatedOn], [LastUpdatedByUser], [LastUpdatedOn])
VALUES (NEWID(), 'EPT10', 'EPC12', 1, 'system', GETDATE(), 'system', GETDATE())
答案 0 :(得分:1)
问题是我的Create + Seed脚本运行了两次种子,并且错误在第二次运行中正确发生。
我以CreateDatabases.cmd dev localhost SeedData.sql
的身份运行它,但是它被设计为始终运行SeedData.sql并可选地运行第三个arg。由于我传递的是“ SeedData.sql”(而不是例如“ SeedData_Stress.sql”),因此它运行了两次。
如果它是“ SeedData.sql”,我将脚本修改为忽略第三个参数:
set Seed=true
if not '%3' == '' (
if '%3' == 'SeedData.sql' ( :: This file will run automatically no matter what, so don't re-run it if it's accidentally passed in
set Seed=false
) else (
set SeedData=%3
)
) else (
set Seed=false
)
...
if %Seed% == true (
echo Adding seed data...
sqlcmd -S %targetServer% -d nexus -E -b -i "%SeedData%"
) ELSE (
echo No additional seed data being added...
)