One-to-One relationships in Entity Framework 7 Code First

Ruben Perez picture Ruben Perez · Feb 19, 2016 · Viewed 13k times · Source

How to configure One-to-One or ZeroOrOne-to-One relationships in Entity Framework 7 Code First using Data Annotations or Fluent Api?

Answer

Sangram More picture Sangram More · Feb 19, 2016

You can define OneToOne relationship using Fluent API in Entity Framework 7 as below

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<BlogImage> BlogImages { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasOne(p => p.BlogImage)
            .WithOne(i => i.Blog)
            .HasForeignKey<BlogImage>(b => b.BlogForeignKey);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogForeignKey { get; set; }
    public Blog Blog { get; set; }
}