using Microsoft.EntityFrameworkCore; namespace BlazorApp1; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql("Host=localhost;Database=testdb;Username=postgres;Password=12345"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Student>() .HasOne<StudentAddress>(s => s.Address) .WithOne(ad => ad.Student) .HasForeignKey<StudentAddress>(ad => ad.AddressOfStudentId); } public DbSet<Student> Students { get; set; } public DbSet<StudentAddress> StudentAddresses { get; set; } } public class Student { public int Id { get; set; } public string Name { get; set; } public StudentAddress Address { get; set; } } public class StudentAddress { public int StudentAddressId { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public int AddressOfStudentId { get; set; } public Student Student { get; set; } }
References
https://www.entityframeworktutorial.net/efcore/configure-one-to-one-relationship-using-fluent-api-in-ef-core.aspx
https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key