EFCore中的多对多外部参照需要手动覆盖?

时间:2017-01-03 03:41:49

标签: c# entity-framework sqlite asp.net-core entity-framework-core

我正在使用efcore + sqlite创建一个应用程序,并努力让我的多对多关系按预期工作。我一直在引用this,但在查询生成的数据库时看到了一些奇怪的行为

以下是有问题的实体:

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

奇怪的是,EF将表生成为SongService(而不是SongServices),因此针对SQLite的查询失败了。不过,其他实体的表格为SongsServices

enter image description here

我不得不用

覆盖
[Table("SongServices")]

任何人都可以解释这种行为吗?是因为它缺少一个ID,所以它不知道如何“分类”表格?

修改 作为参考,这是我的DbContext的样子:

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

0 个答案:

没有答案