soorena12 soorena12 - 1 year ago 303
C# Question

EF core one-to-many relationships HasOne().WithMany() vs HasMany().WithOne()

let's say i have the following 2 models:

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

public List<Post> Posts { get; set; }

public class Post
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

public Blog Blog { get; set; }

now if i want to configure the models relationships in DbContext is there any diffrence between:

.HasOne(p => p.Blog)
.WithMany(b => b.Posts);


.HasMany(b => b.Posts)
.WithOne(p =>;

and if there is a diffrence, what is it? should i write both or just one of them?

As a side note: do i have to define foreign keys? based on my knowledge about databases, you can't create relationships without foreign keys but EF doesn't require you to have foreign key fields so how does EF handles relationships without knowing foreign keys? does it causes performance drops or bugs?

Answer Source

You're right, you can create relations in DbContext without foreign keys in database.


WithOne: One to one relationships have a reference navigation property on both sides. They follow the same conventions as one-to-many relationships, but a unique index is introduced on the foreign key property to ensure only one dependent is related to each principal.

Many-to-many: relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.

You only need to define one relation, because in some cases you'll create a relation for parent-child without navigation properties (one or collection).

For your example: you add a relation for Blog -> Posts because you have navigation properties in both objects, the two lines make the same but in different way:

  • Blog -> Posts (Parent -> child)
  • Posts -> Blog (Child -> Parent)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download