Individual Relationships in Entity Framework 7 Code First

How to set up one-to-one or null-one-to-one relationships in Entity Framework 7 code First use data annotations or free Api?

+8
entity-framework ef-code-first entity-framework-core ef-fluent-api
source share
2 answers

You can define OneToOne relationships using the Fluent API in Entity Framework 7, as shown 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; } } 
+20
source share

The above answer is absolutely correct.

For reader information only: This is well explained in the official documentation.

one to one

One-to-one relationships have link navigation properties on both sides. They follow the same conventions as a one-to-many relationship, but a unique index is entered for the foreign key property to ensure that only one dependent applies to each principal.

 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 BlogId { get; set; } public Blog Blog { get; set; } } 

Note

EF will choose one of the entities that will be dependent, based on its ability to detect a foreign key property. If the wrong object is selected as dependent, you can use the Fluent API to fix this.

+2
source share

All Articles