EF 6 在查询多对多关系时创建不存在表名的查询

问题描述 投票:0回答:1

我有以下课程:

public class Report
{
    [Key]
    public int ReportId { get; set;}

    public virtual ICollection<ReportDataSection> ReportDataSectios { get; } = new DbSet<ReportDataSection>();

    public virtual ICollection<DataSection> DataSections { get; } = new DbSet<DataSection>();

    // Other properties 
}

public class DataSection
{
    [Key]
    public int DataSectionId { get; set; }

    public virtual ICollection<ReportDataSection> ReportDataSections { get; } = new DbSet<ReportDataSection>();

    public virtual ICollection<Report> Reports { get; } = new DbSet<Report>();

    // Other properties
}

public class ReportDataSection
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated( DatabaseGeneratedOption.None)]
    public int ReportId { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated( DatabaseGeneratedOption.None)]
    public int DataSectionId { get; set; }

    public int OrderSeq { get; set; }

    public virtual DataSection { get; set; }

    public virtual Report { get; set; }

}

public class DbModel : DbContext
{
    public virtual DbSet<DataSection> DataSections { get; set; }

    public virtual DbSet<Report> Reports { get; set; }

    protected override OnModelCreating(DbModelBuilder modelBuilder)
    {
        // skipping irrelevant calls

        modelBuilder.Entity<DataSection>()
        .HasMany(e => ReportDataSection)
        .WithRequired(e => e.DataSection)
        .WillCascadeOnDelete(false);

        modelBuilder.Entity<Report>()
        .HasMany(e => ReportDataSection)
        .WithRequired(e => e.Report)
        .WillCascadeOnDelete(false);
    }
}

我正在尝试使用如下代码检索特定

DataSection
的所有数据:

IQueryable<DataSection> query = (from ds in _db.DataSections
                                 where ds.DataSectionId == id
                                 select ds;
query = query.Include(ds => ds.ReportDataSections>)
.Include(ds => ds.Reports);

这会生成一条 SQL 语句,尝试与不存在的表

dbo.ReportDataSections1
连接。

我发现了一个关于“类似问题”的问题,该问题对于 Entity Framework Core 5 具有相同的结果,但涉及自有表。解决方法是在 ModelBuilder 调用中进行更改,但我不知道这在这种情况下是否有效,因为在这种情况下它是多对多关系。

如何让我的查询正常工作?

c# entity-framework entity-framework-6 many-to-many
1个回答
0
投票

public class Report { [Key] public int ReportId { get; set;} public virtual ICollection<DataSection> DataSections { get; set; } // Other properties } public class DataSection { [Key] public int DataSectionId { get; set; } public virtual ICollection<Report> Reports { get; set; } // Other properties } public class DbModel : DbContext { public DbSet<Report> Reports { get; set; } public DbSet<DataSection> DataSections { get; set; } protected override OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Report>() .HasMany(e => DataSections) .WithMany(e => e.Reports) .WillCascadeOnDelete(false); } }

© www.soinside.com 2019 - 2024. All rights reserved.