首页 > 解决方案 > EF Core - 将存储过程结果映射到多个实体

问题描述

我正在尝试创建一个分组的数据集合(深 2 级),这是 JSON 表示:

[
 {
  Year: 2021,
  Houses: [
   {
     HouseName: "Gryffindor",
     Students: [...]
   }
   ...
 ]
}
...
]

Years、Houses 和 Student 是各自独立的实体。我尝试使用GroupBy()and ToLookup(),但它们会减慢响应时间。

我最后一次徒劳的尝试是这样的:

  1. 创建一个 SQL 存储过程,该过程将返回以下格式的扁平行:

     <Year, House, StudentId, StudentName, StudentAge>
    
  2. 使用代码优先方法创建以下实体:

     class YearRow
     {
         public int Year { get; set; }
         public virtual ICollection<HouseSubRow> Houses { get; set; }
     }
    
     class HouseSubRow
     {
         public string HouseName { get; set; }
         public virtual ICollection<StudentInnerMostRow> Students { get; set; }
    
         public int Year { get; set; }
         public virtual YearRow ParentRow { get; set; }  
     }
    
     class StudentInnerMostRow
     {
         public int StudentId { get; set; }
         public string StudentName { get; set; }
         public int StudentAge { get; set; }
    
         public string HouseName { get; set; }
         public virtual HouseSubRow ParentRow { get; set; }
     }
    
  3. OnModelCreating()方法中添加了以下配置:

     modelBuilder.Entity<YearRow>().HasKey(x => x.Year);
    
     modelBuilder.Entity<HouseSubRow>(entity => {
       entity.HasKey(x => x.HouseName);
    
       entity.HasOne(x => x.ParentRow)
           .WithMany(x => x.Houses)
           .HasForeignKey(x => x.Year);
     });
    
     modelBuilder.Entity<StudentInnerMostRow>(entity => {
       entity.HasNoKey();
    
       entity.HasOne(x => x.ParentRow)
           .WithMany(x => x.Students)
           .HasForeignKey(x => x.HouseName);
     });
    
  4. 输出是这种格式

     [
      {
        Year: 2021,
        Houses: [] // empty
      },
      ...
     ]
    

该代码不会引发任何编译或运行时错误,它只是没有映射其他实体。

期待

我希望这个平排

<Year, House, StudentId, StudentName, StudentAge>

将映射到相应的实体:

  1. 年份转到 YearRow
  2. 房子去 HouseSubRow
  3. StudentId、StudentName 和 StudentAge 转到 StudentInnerMostRow

约束

  1. 不能使用GroupBy()ToLookup()。评估不应发生在客户端。
  2. 不能在数据库中创建任何新表,只允许视图和存储过程。

有人能告诉我我是否朝着正确的方向前进吗?

this.dbContext.YearRow.FromSqlInterpolated($"EXEC MySproc")

标签: c#entity-frameworkentity-framework-core

解决方案


推荐阅读