我才刚开始学习Entity Framework代码。我正在尝试使用.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语句上放置一个断点并查看歌曲时,将填充歌曲对象,而不是歌手或乐团对象。
我查看了以下相关问题here,但我无法弄清楚自己在做什么错。任何帮助将不胜感激。
关于卡尔
答案 0 :(得分:0)
乐团和歌手应该是虚拟的。
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; }
}