我有一个带有外键的模型。 .NET Core EF如何使我无法两次向该表输入相同的外键。
public class DolsMcaClientModel
{
[Key]
public int DolsMcaClientID { get; set; }
public int DolsMcaItemID { get; set; }
public virtual DolsMcaItemModel DolsMcaItemModel { get; set; }
public int ClientID { get; set; }
[Required]
public int FileID { get; set; }
public virtual FileModel FileModel { get; set; }
}
在此表中, DolsMcaClientID 是我的身份列,而 DolsMcaItemID 是我的外部列。 DolsMcaItemModel 是我的导航属性。
我无法为不同的客户端输入相同的DolsMcaItemID。 DolsMcaItemID充当表中的主键。但事实并非如此。
ERROR: System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.DolsMcaClientModels' with unique index 'IX_DolsMcaClientModels_DolsMcaItemID'. The duplicate key value is (1).
如果我从表中删除DolsMcaItemID 1项目,那么我可以使用DolsMcaItemId 1将新条目添加到表中,但是对于任何clientID只能添加一次...对于其他任何clientID,我都无法输入DolsMcaItem 1
我的SQL表创建查询是:
CREATE TABLE [dbo].[DolsMcaClientModels](
[DolsMcaClientID] [int] IDENTITY(1,1) NOT NULL,
[DolsMcaItemID] [int] NOT NULL,
[ClientID] [int] NOT NULL,
[FileID] [int] NOT NULL,
CONSTRAINT [PK_DolsMcaClientModels] PRIMARY KEY CLUSTERED
(
[DolsMcaClientID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[DolsMcaClientModels] WITH CHECK ADD CONSTRAINT [FK_DolsMcaClientModels_DolsMcaItemModels_DolsMcaItemID] FOREIGN KEY([DolsMcaItemID])
REFERENCES [dbo].[DolsMcaItemModels] ([DolsMcaItemID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[DolsMcaClientModels] CHECK CONSTRAINT [FK_DolsMcaClientModels_DolsMcaItemModels_DolsMcaItemID]
GO
ALTER TABLE [dbo].[DolsMcaClientModels] WITH CHECK ADD CONSTRAINT [FK_DolsMcaClientModels_FileModels_FileID] FOREIGN KEY([FileID])
REFERENCES [dbo].[FileModels] ([FileID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[DolsMcaClientModels] CHECK CONSTRAINT [FK_DolsMcaClientModels_FileModels_FileID]
GO
答案 0 :(得分:1)
该列上的UNIQUE索引 [IX_DolsMcaClientModels_DolsMcaItemID] 阻止您提交具有相同 [DolsMcaItemID] 的另一条记录。
修正是删除唯一索引:
ALTER TABLE [dbo].[DolsMcaClientModels] DROP INDEX [IX_DolsMcaClientModels_DolsMcaItemID];
CREATE INDEX [IX_DolsMcaClientModels_DolsMcaItemID] ON [dbo].[DolsMcaClientModels] ([DolsMcaItemID])
别忘了搭建数据库上下文,以从代码中删除约束。