c# - EF Core - 将存储过程结果映射到多个实体
问题描述
我正在尝试创建一个分组的数据集合(深 2 级),这是 JSON 表示:
[
{
Year: 2021,
Houses: [
{
HouseName: "Gryffindor",
Students: [...]
}
...
]
}
...
]
Years、Houses 和 Student 是各自独立的实体。我尝试使用GroupBy()
and ToLookup()
,但它们会减慢响应时间。
我最后一次徒劳的尝试是这样的:
创建一个 SQL 存储过程,该过程将返回以下格式的扁平行:
<Year, House, StudentId, StudentName, StudentAge>
使用代码优先方法创建以下实体:
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; } }
在
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); });
输出是这种格式
[ { Year: 2021, Houses: [] // empty }, ... ]
该代码不会引发任何编译或运行时错误,它只是没有映射其他实体。
期待
我希望这个平排
<Year, House, StudentId, StudentName, StudentAge>
将映射到相应的实体:
- 年份转到 YearRow
- 房子去 HouseSubRow
- StudentId、StudentName 和 StudentAge 转到 StudentInnerMostRow
约束
- 不能使用
GroupBy()
或ToLookup()
。评估不应发生在客户端。 - 不能在数据库中创建任何新表,只允许视图和存储过程。
有人能告诉我我是否朝着正确的方向前进吗?
this.dbContext.YearRow.FromSqlInterpolated($"EXEC MySproc")
解决方案
推荐阅读
- swift - 如何从 ViewController.swift 引用函数内的 URL 对象?
- php - Laravel - 将我的普通 PHP 代码转换为 Laravel(控制器和视图)
- ruby-on-rails - 'foreign_key' 关联列的 ActiveAdmin belongs_to
- npm - 启动开发服务器时出现浏览器列表错误
- python - 聚合具有不同功能的字典值
- c++ - 类构造函数比“=”运算符具有更高的优先级?
- vba - 循环遍历 Word 文档并用 PageBreak 替换字符串
- c++ - 代码正在运行,但不会执行 gpu 函数
- java - 当我尝试通过 Buildozer 初始化 android Visualizer 时出现神秘错误
- java - 是否可以在没有刷新令牌的情况下检查 JWT 有效性?