实体框架多对多关系插入不起作用

时间:2015-09-28 18:55:58

标签: c# .net entity-framework

我有两张表有多对多的关系:ActionPlanResponsible

当我插入新的ActionPlan和新的Responsible时,表格ActionPlanResponsible上的记录会正确创建,但是当我尝试添加新的ActionPlan时,Responsible存在ActionPlanResponsible 1}},表{ "What": "Whatttasdasdt", "Why": "Whyasdyyyy", "How": "Hoasdwwwww", "StartDate": "28/09/2015", "EndDate": "28/09/2015", "CreateDate": "28/09/2015", "UpdateDate": "28/09/2015", "State": "1", "Where" : "Whasdere", "Goal": { "Id": "10" }, "Responsibles": [{ "Id": "15" }] 中的记录未创建。

我以一种方式将ActionPlan和Responsible传递给Json:

foreach (var r in actionPlan.Responsibles)
{
    context.Responsible.Attach(r);
}

context.ActionPlan.Add(actionPlan); 

context.SaveChanges();
transaction.Commit();

这就是我在EF中执行请求的方式......

 public long Id { get; set; }

    public string What { get; set; }

    public string Why { get; set; }

    public string How { get; set; }

    public DateTime StartDate { get; set; }

    public virtual ICollection<Responsible> Responsibles { get; set; }

    public DateTime EndDate { get; set; }

    public Goal Goal { get; set; }

    public virtual ICollection<FileActionPlan> Files { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }

    public string Where { get; set; }

    public virtual ICollection<Task> Tasks { get; set; }

ActionPlan实体:

 public byte State { get; set; }

    public DateTime CreateDate { get; set; }

    public DateTime UpdateDate { get; set; }

    //public virtual ICollection<ActionPlan> ActionPlans { get; set; }

    public virtual ICollection<Task> Tasks { get; set; }

    public long Id { get; set; }

    public Guid PersonId { get; set; }

负责实体:

    myEdiText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                    case KeyEvent.KEYCODE_ENTER:
                        Toast.makeText(getApplicationContext(), "ENTER", Toast.LENGTH_LONG).show();
                        return true;
                    case KeyEvent.KEYCODE_DEL:
                    case KeyEvent.KEYCODE_BACK:
                        Toast.makeText(getApplicationContext(), "BACKSPACE", Toast.LENGTH_LONG).show();
                        return true;
                    default:
                        break;
                }
            }
            return false;
        }
    });

1 个答案:

答案 0 :(得分:1)

您还必须将Responsibles添加到actionPlan.Responsibles

foreach (var r in actionPlan.Responsibles)
{
    context.Responsible.Attach(r);
    actionPlan.Responsibles.Add(r);
}

context.ActionPlan.Add(actionPlan); 

这不会创建新的Responsibles但会建立关联,因此EF知道它应该插入连接记录。