Map Many to Many relationship without navigation p

2019-01-08 21:35发布

问题:

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.

回答1:

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");
    });