I have two models in my ASP.NET MVC project. When seeding to include test data I do the following:
context.Dialogs.Add(new Dialog
{
Id = 1,
Chapter = 1,
Index = 0,
DialogColor = "default-color",
DialogText = "blah blah!",
Character = "none",
Transition = false,
Fade = true,
Timer = 0,
Actions = new List<Action>
{
new Action { ActionText = "--continue--", ActionLink = 1, Id=1 }
}
});
This saves the record in the Dialog table but the Actions are not saved, I know I can probably save the dialog first and then append an Action to it but I want to be able to add it all inline like above?
Dialog model:
public class Dialog
{
[Key]
public int Id { get; set; }
public int Chapter { get; set; }
public int Index { get; set; }
public string DialogColor { get; set; }
public string DialogText { get; set; }
public string Character { get; set; }
public bool Transition { get; set; }
public bool Fade { get; set; }
public int Timer { get; set; }
public virtual IEnumerable<Action> Actions { get; set; }
}
Action Model:
public class Action
{
[Key]
public int Id { get; set; }
public string ActionText { get; set; }
public int ActionLink { get; set; }
public Dialog Dialog { get; set; }
}
You need to update your model to use an ICollection so entity framework will make the proper associations. From this post:
In your dialog class update your property to:
EDIT:
Couple other things to look for, are the navigation properties mapped?
You could try adding a fluent mapping:
Is the FK actually getting mapped in the database? Note: The Dialog_Id on the Actions table. If you don’t have this, then EF isn’t actually mapping your relationship
If none of this work, you could always explicitly add the entity to your context when creating it in the list:
The DbSet.Add method will return the entity once it’s been added to the context.