I have a couple of simple models. An PlaylistEntry model and a Playlist model which contains a collection of PlaylistEntry models.
Playlist:
public class Playlist
{
private ICollection<PlaylistEntry> playlistEntries;
public int PlaylistId { get; set; }
public string Name { get; set; }
public virtual ICollection<PlaylistEntry> PlaylistEntries
{
get => this.playlistEntries ?? (this.playlistEntries = new HashSet<PlaylistEntry>());
set => this.playlistEntries = value;
}
}
PlaylistEntry
public class PlaylistEntry
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PlaylistEntryId { get; set; }
public string FilePath { get; set; }
[ForeignKey("Playlist")]
public int PlaylistId { get; set; }
[Required]
public Playlist Playlist { get; set; }
}
When I add a PlaylistEntry to a Playlist in a detached state, I expect that when I attach and save changes, the changes to the PlaylistEntries list will also be saved. They don't save and the list is empty.
Here's my code:
var playlist = new Playlist { Name = "My first playlist" };
using (var context = new MusicPlayerContext(stringBuilder))
{
context.Playlists.Add(playlist);
context.SaveChanges();
}
playlist.PlaylistEntries.Add(new PlaylistEntry { FilePath = "lkdfj", PlaylistId = playlist.PlaylistId });
using (var context = new MusicPlayerContext(stringBuilder))
{
context.Playlists.Attach(playlist);
context.Entry(playlist).State = EntityState.Modified;
context.SaveChanges();
}
using (var context = new MusicPlayerContext(stringBuilder))
{
context.Playlists.Include(x => x.PlaylistEntries).ToList();
}
That last ToList call returns the playlist I create but the PlaylistEntries collection on it is empty.
Can anyone spot what I'm doing wrong or suggest a different solution please? I've spent about 7 hours on this and can't for the life of me figure it out.
Entry
for thePlaylistEntry
object? – Ann L. Feb 9 '19 at 2:28context.PlaylistEntries
, assuming that exists. – Ann L. Feb 9 '19 at 2:30