在 LINQ 中创建数据库时查询数据库中的父参考
Posted
技术标签:
【中文标题】在 LINQ 中创建数据库时查询数据库中的父参考【英文标题】:Parent Reference in Query DB when Creating database in LINQ 【发布时间】:2021-11-11 11:52:42 【问题描述】:我有以下课程
public class Children
public Children () // constructor
public int Id get;set;,
public string ChildName get; set;
public class Parents
public Parents() // constructor
public int Id get;set;,
public string ParentName get;set;
public Children Child get; set;
我想要每个父母 1 个孩子,在我的配置中
public void Configure(EntityTypeBuilder<Parents> configuration)
configuration.ToTable("Parents");
configuration.Property(p => p.Id).HasField("_id");
configuration.HasOne(a => a.ChildClass).WithMany().OnDelete(DeleteBehavior.Cascade);
public void Configure(EntityTypeBuilder<Children> configuration)
configuration.ToTable("Children");
configuration.Property(p => p.Id).HasField("_id");
当我使用实体框架 5 构建器时,我会从数据库中返回 2 个表
CREATE TABLE [dbo].[Parents](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ChildId] [int] NOT NULL,
[ParentName] [nvarchar](max) NULL,
CONSTRAINT [PK_Parents] 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]
ALTER TABLE [dbo].[Parents] WITH CHECK ADD CONSTRAINT
[FK_Parents_Children_Child] FOREIGN KEY([ChildId])
REFERENCES [dbo].[Children] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Parents] CHECK CONSTRAINT [FK_Parents_Parents_Children_ChildId]
GO
CREATE TABLE [dbo].[Children](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ChildName] [nvarchar](max) NULL,
[ParentId] [int] NULL,
CONSTRAINT [PK_Children] 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].[Children] WITH CHECK ADD CONSTRAINT [FK_Children_Parent_ParentId] FOREIGN
KEY([ParentId])
REFERENCES [dbo].[Parents] ([Id])
GO
ALTER TABLE [dbo].[Children] CHECK CONSTRAINT [FK_Children_Parent_ParentId]
GO
基本上我陷入了一个循环,因为我无法插入 Parents
记录,并且我无法插入儿子,因为他们需要两组 Id,我不知道为什么 Children
表需要引用 @987654326 @表,如果父表已经引用了Children
表。
【问题讨论】:
【参考方案1】:根据您的流利映射,您似乎已经建立了一对多的关系,其中每个孩子可以有多个父母。但你实际上想要一个one-to-one relationship。
public class Children
public Children ()
public int Id get;set;
public string ChildName get; set;
public int ParentId get; set;
public Parents Parent get; set;
public class Parents
public Parents()
public int Id get; set;
public string ParentName get; set;
public Children Child get; set;
public void Configure(EntityTypeBuilder<Parents> configuration)
configuration.ToTable("Parents");
configuration.Property(p => p.Id).HasField("_id");
configuration.HasOne(p => p.Child).WithOne(c => c.Parent).HasForeignKey<Children>(c => c.ParentId).OnDelete(DeleteBehavior.Cascade);
但是,生成的 SQL 似乎与您的模型和流畅的配置都不匹配。
【讨论】:
以上是关于在 LINQ 中创建数据库时查询数据库中的父参考的主要内容,如果未能解决你的问题,请参考以下文章