Is is possible to map a many to many relationship without having a navigation property on one of the ends? For example I have some widgets and some users who can star particular widgets. I'd like to be able to see what widgets a user cares stars, but I don't really care about seeing all the users who have starred a particular widget
Widget.cs
public int Id { get; set; }
public string Name { get; set; }
User.cs
public int Id { get; set; }
public string Username { get; set; }
public ICollection<Widget> StarredWidgets { get; set; }
With this setup, EF will generate a one-to-many relationship from Widgets to Users. However, it needs to be a many to many. I realize I could add a public ICollection<User> Users
to Widget.cs
, but just seeing if there was another way around this.
The most common pattern for relationships is to have navigation properties defined on both ends of the relationship and a foreign key property defined in the dependent entity class. If a pair of navigation properties is found between two types, then they will be configured as inverse navigation properties of the same relationship.
This indicates that there is conceptually a reference or collection on the other end of the relationship, but there is no navigation property included in the entity class. This feature was introduced in EF Core 5.0. After the navigation property has been created, you may need to further configure it.
This mapping would not use any joined entity. @ManyToMany would be placed on one side for unidirectional or on both side for bidirectional mapping
There are several ways to map Many To Many relationship in JPA and Hibernate by using @ManyToMany, @OneToMany, and @ManyToOne, including Joined entity unidirectional and bidirectional mapping with a single primary key, @OneToMany, and @ManyToOne
You can and this case must define the many-to-many relationship with Fluent API:
modelBuilder.Entity<User>()
.HasMany(u => u.StarredWidgets)
.WithMany() // <- no parameter here because there is no navigation property
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("WidgetId");
m.ToTable("UserWidgets");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With