在EF CF中播种和保存数组

时间:2012-08-26 08:52:24

标签: c# .net entity-framework ef-code-first

我的ASP.NET MVC项目中有两个模型。播种时包括测试数据,我会执行以下操作:

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 }
    }
});

这会将记录保存在Dialog表中,但不保存Actions,我知道我可以先保存对话框,然后向它添加一个Action但我希望能够像上面那样内联添加它吗?

对话模型:

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; }
}

动作模型:

public class Action
{
    [Key]
    public int Id { get; set; }
    public string ActionText { get; set; }
    public int ActionLink { get; set; }

    public Dialog Dialog { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您需要更新模型以使用ICollection,因此实体框架将进行正确的关联。从post

开始
  

实体框架不支持收集属性   使用Add和Remove方法以IEnumerable公开。

在对话框类中,将您的属性更新为:

 public virtual ICollection<Action> Actions { get; set; }

修改

还有其他要寻找的东西,是否映射了导航属性?

您可以尝试添加流畅的映射:

  protected override void OnModelCreating( DbModelBuilder modelBuilder )
  {
     modelBuilder.Entity<Dialog>()
        .HasMany(d => d.Actions)
        .WithOptional(a => a.Dialog);

  }

FK实际上是否已映射到数据库中?注意:Actions表上的Dialog_Id。如果你没有这个,那么EF实际上并没有映射你的关系

enter image description here

如果这些都不起作用,您可以在列表中创建实体时将该实体显式添加到您的上下文中:

     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>
            {
                context.Actions.Add(new Action()
                                       {
                                          ActionText = "--continue--",
                                          ActionLink = 1, Id=1 
                                       })
            }
     } );

DbSet.Add方法将在实体添加到上下文后返回该实体。