【发布时间】:2020-02-07 10:36:48
【问题描述】:
我有一个名为 Company
的表SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Companies](
[Id] [uniqueidentifier] NOT NULL,
[ActiveStatus] [nvarchar](max) NULL,
[Name] [nvarchar](max) NULL,
[Address] [nvarchar](max) NULL,
[Phone1] [nvarchar](max) NULL,
[Phone2] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL,
[CompanyId] [uniqueidentifier] NOT NULL,
[IsParent] [nvarchar](max) NULL,
CONSTRAINT [PK_Companies] PRIMARY KEY CLUSTERED
(
[Id] 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].[Companies] WITH CHECK ADD CONSTRAINT [FK_Companies_Companies_CompanyId] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Companies] ([Id])
GO
ALTER TABLE [dbo].[Companies] CHECK CONSTRAINT [FK_Companies_Companies_CompanyId]
GO
我首先使用ASP.NET Core 代码制作了这个,这是我的课
public class BaseClass
{
[Key]
public Guid Id { get; set; }
public string ActiveStatus { get; set; }
}
public class Company: BaseClass
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone1 { get; set; }
public string Phone2 { get; set; }
public string Email { get; set; }
[ForeignKey("Company")]
public Guid CompanyId { get; set; }
public Company ParentCompany { get; set; }
public string IsParent { get; set; }
public ICollection<Company> ParentCompanies { get; set; }
public ICollection<Activity> Activities { get; set; }
public ICollection<Order> Orders { get; set; }
public ICollection<Ticket> Tickets { get; set; }
public ICollection<User> Users { get; set; }
}
我想使用查询向我的表中插入数据
INSERT [dbo].[Companies] ([Id], [ActiveStatus], [Name], [Address], [Phone1], [Phone2], [Email], [CompanyId], [IsParent]) VALUES (N'af85a23c-3832-47c9-3efe-08d79f1b5659', N'Active', N'PT. Sari Coffee Indonesia', N'Sahid Sudirman Center 27th Floor, Jl. Jend. Sudirman No.Kav. 86, RT.10/RW.11, Karet Tengsin, Kota Jakarta Pusat, Daerah Khusus Ibukota Jakarta 10220', N'+62 21 574 6501', N'+62 21 574 5808', N'feedback@starbucks.co.id', N'00000000-0000-0000-0000-000000000000', N'1')
GO
但是我得到了一个错误:
消息 547,级别 16,状态 0,第 3 行 INSERT 语句冲突 具有 FOREIGN KEY SAME TABLE 约束 “FK_Companies_Companies_CompanyId”。数据库发生冲突 “CRMandOMS”,表
"dbo.Companies",列'Id'。该声明有 被终止了。
请帮忙
【问题讨论】:
-
表中好像没有id = '00000000-0000-0000-0000-000000000000'的行,所以FK没有实现。
-
@jarlh 那我该怎么办?
-
FK 用于确保仅存储有效/已知的 CompanyId。 (即现有的 ID。)您为什么要尝试存储未知的 CompanyId?
-
@jarlh 我不是,我实际上是在搞乱我的代码,我添加了一些 ICollection,然后迁移和更新数据库,因为上次它不是自引用的。所以我要么给一个 null 要么 000 guid
-
或许你应该在这里存储 null ?
标签: c# asp.net-core entity-framework-core