Joe
Joe

Reputation: 5487

EF6 One To Many Fluent Mapping

In EF6, given that these two approaches seem to function identically, are there any advantages in choosing one approach over the other?

modelBuilder.Entity<Player>()
            .HasRequired(p => p.CurrentTeam)
            .WithMany(t => t.Players)
            .HasForeignKey(p => p.CurrentTeamId)
            .WillCascadeOnDelete(false);

is the same as

modelBuilder.Entity<Team>()
            .HasMany(t => t.Players)
            .WithRequired(p => p.Team)
            .HasForeignKey(p => p.CurrentTeamId)
            .WillCascadeOnDelete(false);

Is this just a matter of personal preference?

Upvotes: 2

Views: 487

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205539

I fully agree with all points from @CodeNotFound answer. But there is one case (not with your sample) where it's not a matter of preference, but a must choosing one of them - unidirectional relatioships, i.e. when navigation property exists only in one of the relationships ends.

In such case, since EF6 Has methods require navigation property expression while With methods have overloads with and without navigation property, you are forced to start configuration from the entity with navigation property (in contrast, EF Core have no such requirements, so there it's really a matter of preference).

So in case you don't have collection navigation property, the only choice is:

modelBuilder.Entity<Player>()
    .HasRequired(p => p.CurrentTeam)
    .WithMany() // <--
    .HasForeignKey(p => p.CurrentTeamId)
    .WillCascadeOnDelete(false);

and if you don't have reference navigation property, respectively:

modelBuilder.Entity<Team>()
    .HasMany(t => t.Players)
    .WithRequired() // <--
    .HasForeignKey(p => p.CurrentTeamId)
    .WillCascadeOnDelete(false);

Note that it's crucial to use the correct With overload. For instance, if you do have navigation property and you don't specify it, EF will map it to another unidirectional relationship with conventionally named FK shadow property.

Upvotes: 3

CodeNotFound
CodeNotFound

Reputation: 23190

Is this just a matter of personal preference?

Yep. It is just a matter of personal preference.

Some people say : A player belong to one team (which is his current team).

Others can just say: A team is composed of many players.

For EF, the two configurations are just setting the same things: A one to many relational ship no matter which entity you use to start the configuration.

The two configurations can exist as long as they are saying the same thing but just keep one of them.

Upvotes: 1

Related Questions