Collection in entity framework model is not updating

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.


The feature you're missing is how the Context Cache works. When you attach an entity (either manually or by requesting an entity from the database) to the context, it's watched by entity framework for changes and tracking those changes.

You've added an object to an entitiy's propety, then added it to the context. Entity Framework is now watching it for changes to do any additional work. All objects added this way are marked as unchanged. Marking the parent changed does not mark the navigation properties as changed.

You can either add the entity to the property inside the context:

using (var context = new MusicPlayerContext())
{
    Console.WriteLine("Save PlayList 2 (in context add)");
    context.Playlists.Attach(playlist3);
    playlist3.PlaylistEntries.Add(new PlaylistEntry { 
      FilePath = "Entry3", 
      PlaylistId = playlist3.PlaylistId, PlaylistEntryId = 3 
    });
    context.SaveChanges();
}

... OR mark both objects entries after attaching the parent.

using (var context = new MusicPlayerContext())
{
    Console.WriteLine("Save PlayList 2 (full attach)");
    context.Playlists.Attach(playlist2);
    context.Entry(playlist2).State = EntityState.Modified;
    context.Entry(playlist2.PlaylistEntries.First()).State = EntityState.Added;
    context.SaveChanges();
}

In both cases Entity Framework now knows what to do in the DB when SaveChanges() occurs.

DotNetFiddle

[SOLVED], The feature you're missing is how the Context Cache works. When you attach an entity (either manually or by requesting an entity from the� Updating the database and clicking "update" will update the SSDL but won't necessarily make the required changes automatically to the conceptual model, you may need to open up the edmx is the designer and check the properties on the field.


Whenever you are calling context.SaveChanges(); just after adding only PlayList without PlaylistEntries, Entity Framework sending the command to the database and resetting the context state. So after that adding PlaylistEntries to the PlayList would not make any effect. To insert PlaylistEntries with Playlist write your code as follows:

var playlist = new Playlist { Name = "My first playlist" };
using (var context = new MusicPlayerContext(stringBuilder))
{
    playlist.PlaylistEntries.Add(new PlaylistEntry { FilePath = "lkdfj", PlaylistId = playlist.PlaylistId }); // Even you don't need to specify `PlaylistId` here. EF can map it.
    context.Playlists.Add(playlist);
    context.SaveChanges();
}

Hope this will work for you.

Tutorial: Update related data with EF in an ASP.NET MVC app , For many-to-many relationships, the Entity Framework doesn't expose the item, because for a new course the department is not established yet: Since the view doesn't have a collection of Course entities, the model binder� The newly created context is not aware of the Department model. Hence it won’t update the database if you call SaveChanges. To update this entity we need to attach the Department to the context and inform it to mark its status as Modified. Now if we call the SaveChanges method, the context will send an update query to the database.


I've decided to add new entries to the list from within the context like the other answers have suggested. If anyone still wants to know how to get this working in a detached state, here's how:

var playlist = new Playlist { Name = "My first playlist" };

using (var context = new MusicPlayerContext(stringBuilder))
{
    context.Playlists.Add(playlist);
}

playlist.PlaylistEntries.Add(new PlaylistEntry { FilePath = "Song7" });
playlist.PlaylistEntries.Add(new PlaylistEntry { FilePath = "Song8" });

using (var context = new MusicPlayerContext(stringBuilder))
{
    context.Playlists.Add(playlist);
    context.Entry(playlist).State = EntityState.Modified;

    foreach (var entry in playlist.PlaylistEntries)
    {
        context.Entry(entry).State = entry.PlaylistEntryId == 0 ? EntityState.Added : EntityState.Modified;
    }

    context.SaveChanges();
}

using (var context = new MusicPlayerContext(stringBuilder))
{
    context.Playlists.Include(x => x.PlaylistEntries).ToList();
}

The context.Playlists.Add(playlist) doesn't actually add a new playlist. From what I understand, it attaches the playlist and all of the new entries on it. If I don't use Add, I get an error because the PlaylistEntryID of the new entries are all set to 0 by default.

Update Data in Disconnected Scenario in Entity Framework Core, Learn how to update data using Entity Framework Core in a disconnected the DbContext is not aware of the entities because entities were modified out of the UpdateRange, Attach collection of entities to DbContext with Modified state. Configuring Entity Framework through fluent API sometimes is quite hard. In this article I am showing how to configure it to handle entity's child collections that those properly gets added and removed from collection.


Modifying data via the DbContext, Update method (which is new in EF Core); using the DbContext. the fact that the context will begin tracking any related entities (such as a collection of Attach method on an entity, it's state will be set to Unchanged , which will result in no in Entity Framework Core � Fluent API Configuration � Generating a model from an� Double-click on the ProductModel.tt file to open it in the Visual Studio editor. Find and replace the two occurrences of “ ICollection ” with “ ObservableCollection ”. These are located approximately at lines 296 and 484. Find and replace the first occurrence of “ HashSet ” with “ ObservableCollection ”.


[SOLVED], edmx file and not the conceptual model. When changes are made to the definition of existing objects, only the storage model is updated; the� An entity can be in one of five states as defined by the EntityState enumeration. These states are: Added: the entity is being tracked by the context but does not yet exist in the database; Unchanged: the entity is being tracked by the context and exists in the database, and its property values have not changed from the values in the database


Entity Framework will only save navigation properties for new , For new items, I can add a child navigation set with no issues. For updated items, I tried to pass in a completely new collection to overwrite the list,� Starting with Entity Framework 5.0, that is based on .NET 4.5, you can set the relationship to null without loading the related end. You can also set the current value to null using the following method. context.Entry(course).Reference(c => c.Department).CurrentValue = null; By deleting or adding an object in an entity collection.