gpt4 book ai didi

c# - 相同属性的外键已存在

转载 作者:行者123 更新时间:2023-12-04 17:29:50 27 4
gpt4 key购买 nike

我有表 1 和表 2。

Table1 有一个 foreignKey 指向 Table2 主键。这可能是一个糟糕的设计,但我无法更改它,因为它已经过时了。

现在我想先将 EF 与代码一起使用,并尝试通过以下命令为其生成模型和 DbContext 类:

dotnet ef dbcontext scaffold "Server=Server1;Database=DBName;Integrated Security=True;MultiSubnetFailover=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

出现以下错误:

The foreign key {'ForeignKeyId'} cannot be added to the entity type 'TABLENAME' because a foreign key on the same properties already exists on entity type 'TABLENAME' and also targets the key {'FOREIGNKEY'} on 'FOREIGNKEY_PrimaryTable'.

有什么方法可以克服这个错误吗?

最佳答案

我不知道你是否成功完成了这项工作,或者你是否需要它,但既然我是从谷歌来的(前 3 个结果),我会写下我是如何解决这个问题的。也许它对将来的某个人有帮助。

对我来说,这是因为我有 2 个外键但为它们生成了 3 个约束

查看给定表的脚本后:

CREATE TABLE [dbo].[VacationBooking](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[VacationType] [bigint] NOT NULL,
[StartDateTime] [datetime] NOT NULL,
[EndDateTime] [datetime] NOT NULL,
[User] [bigint] NOT NULL,
[Employee] [bigint] NOT NULL,
[Status] [int] NOT NULL CONSTRAINT [DF_VacationBooking_Status] DEFAULT ((0)),
[IsSameDayVacation] [bit] NOT NULL CONSTRAINT [DF_VacationBooking_IsSameDayVacation] DEFAULT ((0)),
[NumberOfHoursAbsent] [decimal](5, 2) NOT NULL CONSTRAINT [DF_VacationBooking_NumberOfHoursAbsent] DEFAULT ((0.00))
CONSTRAINT [PK_VacationBooking] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

GO


-- Constraint 1
ALTER TABLE [dbo].[VacationBooking] WITH CHECK ADD CONSTRAINT [FK_VacationBooking_User] FOREIGN KEY([User])
REFERENCES [dbo].[User] ([Id])
GO

ALTER TABLE [dbo].[VacationBooking] CHECK CONSTRAINT [FK_VacationBooking_User]
GO

-- Constraint 2
ALTER TABLE [dbo].[VacationBooking] WITH CHECK ADD CONSTRAINT [FK_VacationBooking_User1] FOREIGN KEY([Employee])
REFERENCES [dbo].[User] ([Id])
GO

ALTER TABLE [dbo].[VacationBooking] CHECK CONSTRAINT [FK_VacationBooking_User1]
GO


-- Constraint 3
ALTER TABLE [dbo].[VacationBooking] WITH CHECK ADD CONSTRAINT [FK_VacationBooking_User2] FOREIGN KEY([Employee])
REFERENCES [dbo].[User] ([Id])
GO

ALTER TABLE [dbo].[VacationBooking] CHECK CONSTRAINT [FK_VacationBooking_User2]
GO

我需要有 2 个 FK 到 User 表(一个用于 author,一个用于它所关注的 employee),但是应该有只有那么 2 个约束条件。

我删除后

Constraint 3

从我的表中,我可以成功搭建数据库。

关于c# - 相同属性的外键已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60776558/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com