Reputation: 3698
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)?
Upvotes: 3
Views: 4482
Reputation: 1
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; }
}
Upvotes: 0
Reputation: 2629
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.
Upvotes: 1
Reputation: 5018
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)
Upvotes: 0
Reputation: 28434
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 :)
Upvotes: 0