c# - 实体框架代码优先 - 无法使用包含检索嵌套对象
问题描述
我刚刚开始学习实体框架代码优先。我正在尝试使用.Include
语法来获取相关对象。我已经能够成功地将对象从一对多关系中检索到列表中,但不能让它从多对一关系中工作。所以我有一首歌,它有一个相关的管弦乐队和一个相关的歌手
对象定义
public class Song
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("OrchestraId")]
public Orchestra Orchestra { get; set; }
public int OrchestraId { get; set; }
[ForeignKey("SingerId")]
public Singer Singer { get; set; }
public int SingerId { get; set; }
public int Genre { get; set; }
public string Year { get; set; }
public Song()
{
this.Orchestra = new Orchestra();
this.Singer = new Singer();
}
}
public class Singer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Orchestra
{
public int Id { get; set; }
public string Name { get; set; }
}
我有一个上下文对象
public class POCContext : DbContext
{
public DbSet<Singer> Singers { get; set; }
public DbSet<Orchestra> Orchestras { get; set; }
public DbSet<Song> Songs { get; set; }
}
我用来获取歌曲的代码如下
public Song GetSong(int songId)
{
Song song = new Song();
song = _context.Songs.Include(s => s.Orchestra)
.Include(s => s.Singer)
.Single(s => s.Id == songId);
return song;
}
当我在 return 语句上设置断点并查看歌曲时,会填充歌曲对象,但不会填充歌手或管弦乐队对象。
我在这里查看了以下相关问题,但我无法弄清楚我做错了什么。任何帮助是极大的赞赏。
问候卡尔
解决方案
管弦乐队和歌手应该是虚拟的。
public virtual Orchestra Orchestra { get; set; }
public virtual Singer Singer { get; set; }
这是一个示例配置:
public class Song
{
[Key]
public Guid Id { get; set; }
public string Title { get; set; }
//navigation property
public virtual List<Singer> Singers { get; set; }
}
public class Singer
{
[Key]
public int Id { get; set; }
[ForeignKey("Song")]
[Required]
public string SongId { get; set; }
[Required]
public string Name { get; set; }
//navigation property
public virtual Song Song { get; set; }
}
推荐阅读
- css - 确定在使用 -webkit-line-clamp 进行多行省略号时是否显示省略号
- java - Spring Cloud Service 向 Discovery Server 注册,但随后取消注册并停止
- sparql - SPARQL - 查询 DBpedia 中事物的任何信息
- macos - Mac OSX 上的 snap web 框架 (Haskell) 在哪里安装
- python - 使用 Pandas,我们如何将状态的初始值复制到每一行作为新列
- wpf - 在 WPF 应用程序中删除文本后,如何在 keydown 事件上检测文本框的高度
- scala - Scala反转地图,新值是重复键的列表
- cassandra - Cassandra tablestats 显示完全修复后修复率为 0.0%
- python - 使用 pd.DataFrame(ticker: data.c) 获取 SyntaxError
- kotlin - 如何使用不可变转换在 Kotlin 中反转地图