Mid EF Core

How to configure a one-to-one relationship in EF Core?

Example using Fluent API:

modelBuilder.Entity<User>()

.HasOne(u => u.Profile)

.WithOne(p => p.User)

.HasForeignKey<Profile>(p => p.UserId);

Or with data annotations:

public class Profile

[Key, ForeignKey("User")]

public int UserId { get; set; }

public User User { get; set; }

  • Requires a unique foreign key.
  • EF assumes optional by default unless marked as required.

More from Entity Framework Core Tutorial

All questions for this course