Search code examples
c#entity-frameworkentity-framework-6

Entity Framework Update nested list


I use Entity Framework 6 (Code First). I have a class:

public class DialogSession {...}

And another class with a list of DialogSession objects:

public class DialogUser
{
    public int Id { get; set; }
    public List<DialogSession> DialogSessions { get; set; }
}

I add DialogSession object to the list and then execute context.SaveChanges() as follows:

dialogUser.DialogSessions.Add(dialogSession);
context.SaveChanges();

But the foreign key of the dialogSession record still Null:

enter image description here

I've tried using many methods on the web like the follows but withoyt success:

context.DialogUsers.Attach(dialogUser);
context.Entry(dialogUser).State = EntityState.Modified;
context.SaveChangesExtention();

Does anyone know how to save inner objects (like the list) in the database using Entity Framework (6)?


Solution

  • From your question is not clear which relationship type do you have, so I guess you have One-to-Many and something like this should works:

    public class DialogSession
    {
        public int DialogSessionId { get; set; }
        public virtual DialogUser DialogUser { get; set; }
    }
    
    public class DialogUser
    {
        public int DialogUserId { get; set; }
        public virtual ICollection<DialogSession> DialogSessions { get; set; }
    }
    

    Take a look at example how properly configure this type of relationship in this article.