I am creating an application using efcore + sqlite and struggling to get my many-to-many relationships to work as expected. I've been referencing this but seeing some strange behavior when querying against the resulting database
Here's the entities in question:
public class Song
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/* Snip Properties */
public ICollection<SongService> SongServices { get; set; }
}
public class Service
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/* Snip Properties */
public ICollection<SongService> SongServices {get;set;}
}
public class SongService
{
public int SongId {get;set;}
public Song Song {get;set;}
public int ServiceId {get;set;}
public Service Service {get;set;}
}
Strangely, EF generated the table as SongService (rather than SongServices) so the queries against SQLite were failing. The table for the other entities were Songs
and Services
, though.
I had to override with
[Table("SongServices")]
Can anyone explain this behavior? Is it because it's missing an ID so it doesn't know how to 'classify' the table?
EDIT: For reference, this is what my DbContext looks like:
public class OnKeyContext : DbContext
{
public DbSet<Song> Songs { get; set; }
public DbSet<Service> Services { get; set; }
public DbSet<SongService> SongServices { get; set; }
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SongService>()
.HasKey(ss => new { ss.ServiceId, ss.SongId });
modelBuilder.Entity<SongService>()
.HasOne(ss => ss.Song)
.WithMany(s => s.SongServices)
.HasForeignKey(ss => ss.SongId);
modelBuilder.Entity<SongService>()
.HasOne(ss => ss.Service)
.WithMany(s => s.SongServices)
.HasForeignKey(ss => ss.ServiceId);
}