'EF Core one-one relationships
I need to configure following one-one relationship with ef-core
public class Player
{
public long Id { get; set; }
public string Name { get; set; }
public long? ProPlayerId { get; set; }
public ProPlayer ProPlayer { get; set; }
}
public class ProPlayer
{
public long Id { get; set; }
public string Name { get; set; }
public long PlayerId { get; set; }
public Player Player { get; set; }
}
Here is the table design I need to have with above code.
CREATE TABLE Player(
ID INT PRIMARY KEY,
ProPlayerId INT NULL
);
CREATE TABLE ProPlayer(
ID INT PRIMARY KEY,
PlayerId INT FOREIGN KEY REFERENCES Player(ID)
);
ALTER TABLE Player
ADD CONSTRAINT FK_Player_ProPlayer FOREIGN KEY (ProPlayerId) REFERENCES ProPlayer(ID);
I have tried with several entity configurations to achieve above but none of them works. Does any one have an idea about how to configure relationships to achieve above. Thanks.
Here is my DbContext
public class ResearchContext : DbContext
{
public ResearchContext(DbContextOptions dbContextOptions) : base(dbContextOptions)
{
}
public DbSet<Player> Players { get; set; }
public DbSet<ProPlayer> ProPlayers { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ProPlayer>()
.HasOne(x => x.Player)
.WithOne(x => x.ProPlayer)
.HasForeignKey<ProPlayer>(x => x.PlayerId);
builder.Entity<Player>()
.HasOne(x => x.ProPlayer)
.WithOne(x => x.Player)
.HasForeignKey<Player>(x => x.ProPlayerId); ;
}
}
Here is the schema I got with above migration
CREATE TABLE [dbo].[Players](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[ProPlayerId] [bigint] NULL,
CONSTRAINT [PK_Players] PRIMARY KEY CLUSTERED
(
[Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Players] WITH CHECK ADD CONSTRAINT
[FK_Players_ProPlayers_ProPlayerId] FOREIGN KEY([ProPlayerId])
REFERENCES [dbo].[ProPlayers] ([Id])
GO
ALTER TABLE [dbo].[Players] CHECK CONSTRAINT
[FK_Players_ProPlayers_ProPlayerId]
GO
CREATE TABLE [dbo].[ProPlayers](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[PlayerId] [bigint] NOT NULL,
CONSTRAINT [PK_ProPlayers] PRIMARY KEY CLUSTERED
([Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Simply I need foreign keys on bothsides. Is it possible to do it with EF core.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|