I have 2 classes in C#. The problem is EF Core maps relation of one-to-one to one-to-many to the Postgresql database.
public class User
{
public string Id { get; set; }
public Subscription Subscription { get; set; } = null!;
}
public class Subscription
{
public string Id { get; set; }
public string UserId { get; set; }
public User User { get; set; } = null!;
}
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasOne(u => u.Subscription)
.WithOne(sub => sub.User)
.HasForeignKey<Subscription>(sub => sub.UserId);
}
}
I tried to implement a one-to-one relation between User
and Subscription
, but I am getting a one-to-many relationship in the database.
Your code is well-configured, and the one-to-one relationship is correctly established.
When creating a one-to-one relationship in your database, you typically need to enforce a unique constraint on the foreign key in the dependent table to ensure that each record in the dependent table corresponds to exactly one record in the principal table. This is done by creating a unique index.
After adding the migration to the database, you will see that such an index is built:
migrationBuilder.CreateIndex(
name: "IX_Subscriptions_UserId",
table: "Subscriptions",
column: "UserId",
unique: true);
Try experimenting with the data, and you will see the relationship in action.