I'm making a project which requires many-to-many relationships. I know that in order to do this, you should create join tables.
In my project we have users, series and episodes. We will ignore the episodes for simplicity here. The users have favorite series and a watchlist.
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string FullName { get; set; }
public List<UserSeries> WatchList { get; }
public List<UserSeries> FavoriteSeries { get; }
}
The join entity:
public class UserSeries
{
public int UserId { get; set; }
public User User { get; set; }
public int SeriesId { get; set; }
public Series Series { get; set; }
}
The Series entity is not that important, it's a standard type of entity.
Now Im trying to make configurations for EF Core, I do this with Fluent API Configurations (IEntityTypeConfiguration). I first tried to make a UserSeriesConfiguration like this:
class UserSeriesConfiguration : IEntityTypeConfiguration<UserSeries>
{
public void Configure(EntityTypeBuilder<UserSeries> builder)
{
builder.ToTable("UserSeries");
builder.HasKey(us => new { us.UserId, us.SeriesId });
builder.HasOne(us => us.User).WithMany(u => u.FavoriteSeries).HasForeignKey(ue => ue.UserId);
builder.HasOne(us => us.User).WithMany(u => u.WatchList).HasForeignKey(us => us.UserId);
builder.HasOne(us => us.Series).WithMany().HasForeignKey(us => us.SeriesId);
}
}
EF Core complained:
Cannot create a relationship between 'User.WatchList' and 'UserSeries.User', because there already is a relationship between 'User.FavoriteSeries' and 'UserSeries.User'. Navigation properties can only participate in a single relationship.
I tried making a UserFavoriteSeriesConfiguration and a UserWatchListConfiguration, and give them seperate table names, but this is rather ugly, makes for duplicate code and lots of extra configuration classes (especially because with episodes etc. I have this setup too), and worst of all: it still didn't work...
Is there a simple solution to this problem? Worst case I will have to make join entities (in stead of UserSeries can then make UserFavoriteSeries), but this is doubling down on the negatives I described in the previous paragraphs: lots of extra classes and duplicate code.


