简体   繁体   中英

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:

在此处输入图片说明

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

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 .

If I am not wrong you should add

dialogUser.DialogSessions.Add(dialogSession);
context.Entry(dialogUser).State = EntityState.Modified; 
context.SaveChanges();

This will mark the entity as modified and then the changes should be reflected on the db.

This could be done a more efficiently by marking singular properties as modified

dialogUser.DialogSessions.Add(dialogSession);
context.Entry(dialogUser).Property(u => u.dialogSession).IsModified = true; 
context.SaveChanges();

Give it a try :)

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)

The below works for me.

using System.ComponentModel.DataAnnotations;

public class DialogSession
{
    [Key]
    public int DialogSessionId { get; set; }
    public int DialogUser { get; set; }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM