Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Many to Many relationship without navigation property

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.

like image 204
Kyle Avatar asked May 23 '13 16:05

Kyle


People also ask

How are navigation properties configured in a relationship?

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.

Why is there no navigation property in the entity class?

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.

Does @manytomany mapping use any joined entity?

This mapping would not use any joined entity. @ManyToMany would be placed on one side for unidirectional or on both side for bidirectional mapping

How to map many to many relationship in JPA and hibernate?

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


1 Answers

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");
    });
like image 79
Slauma Avatar answered Oct 05 '22 03:10

Slauma