By now, we should be able to say that relationships are identified by Entity Framework while it is analyzing our data model. So, from the preceding section, it is evident that we should have a navigation property in both the entities for a relationship.
While analyzing the relationship, Entity Framework can only identify a primary key on its own. But, if we use an alternate key for a relationship, then explicitly we should mark it as the principal key using the Fluent API. In our blogging system, the implementation in OnModelCreating would be as follows:
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.BlogUrl)
.HasPrincipalKey(b => b.Url);
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.BlogUrl)
.HasPrincipalKey(b => b.Url);
It's also evident that, for any relationship, we need a property that should be against a data model and not a scalar datatype (it would be ignored...