I am just starting to learn Entity Framework code-first. I am trying to use the .Include
syntax to get related objects. I have been able to successfully retrieve objects into a list from a one to many relationship, but can't get it to work from a many to one relationship. So I have a song, which has a related orchestra and a related singer
The object definitions
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; }
}
I have a context object
public class POCContext : DbContext
{
public DbSet<Singer> Singers { get; set; }
public DbSet<Orchestra> Orchestras { get; set; }
public DbSet<Song> Songs { get; set; }
}
The code I use to get a song is the following
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;
}
When I put a breakpoint on the return statement and look at the song, the song object is populated, but not the singer or orchestra objects.
I had a look at the following related question here but I have not been able to work out what I am doing wrong. Any help is greatly appreciated.
regards Carl