We already had a sneak peek into the Fluent API, without which the relationship can never be complete (in a few cases, it is mandatory).
We used the Fluent API in one-to-one and many-to-many relationships. We will use the same method to leverage the terminologies we have seen so far. The HasOne
and HasMany
methods allow us to identify the navigation property in the dependent entity or simply a reference navigation property.
The following code configures the foreign key explicitly in the one-to-many relationship:
modelBuilder.Entity<TagPost>()
.ToTable("TagPost")
.HasOne(x => x.Tag)
.WithMany(x => x.TagPosts)
.HasForeignKey(x => x.TagId);
The following diagram, the TagId
highlighted is required for the foreign key of the relationship:
The HasOne
method identifies the Tag
navigation in the TagPost
entity. The WithOne
and WithMany
methods allow us to identify the inverse...