Entity Framework Update nested list

c# entity-framework entity-framework-6

Question

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)?

1
0
12/12/2016 12:06:43 AM

Accepted Answer

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.

1
12/13/2016 6:02:16 PM

Popular Answer

Please see: https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx

You should use a virtual list for the child entity, and ensure that the DialogSessions class also refers back to its parent with a DialogUserId property (so named by convention)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow