C# INSERT语句与外键同表约束冲突| ASP.NET Core&;实体框架核心代码优先

C# INSERT语句与外键同表约束冲突| ASP.NET Core&;实体框架核心代码优先,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我有一张名为公司的桌子 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, [Phon

我有一张名为公司的桌子

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核心代码制作了这个,这是我的课程

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; }
    }
但我有一个错误:

Msg 547,16级,状态0,第3行INSERT语句冲突 具有外键的同一表约束 “FK公司”。数据库中发生冲突 “CRMandOMS”,表
“dbo.companys”
,列
“Id”
。该声明已经发布 已经终止


请帮助您想将
00000000-0000-0000-0000-000000000000
添加为
CompanyId
,因此您面临此错误,因为在您的表中没有具有此
Id的公司

在您的场景中,可能有一家公司没有母公司,因此您的表设计是错误的。要解决此错误,必须使
公司ID
外键
可为空

你可以这样做:

...

[ForeignKey("Company")]
public Guid? CompanyId { get; set; }

...
然后
添加迁移
更新数据库
以更改数据库。现在,您可以插入母公司为
Null
的公司


祝你好运

表中似乎没有id为“00000000-0000-0000-0000-000000000000”的行,因此FK没有实现。@jarlh那么我该怎么办?FK的存在是为了确保只存储有效/已知的CompanyId。(即现有Id)为什么要存储未知的CompanyId?@jarlh我没有,我实际上是在乱搞我的代码,我添加了一些ICollection、迁移和更新数据库,因为上次它不是自引用的。所以要么我给一个null,要么给1000个guidPerhaps,你应该在这里存储null?
...

[ForeignKey("Company")]
public Guid? CompanyId { get; set; }

...