简体   繁体   中英

Entity Framework many to many relationship insert not working

I have two tables with many to many relationship: ActionPlan and Responsible .

When I insert a new ActionPlan and new Responsible , the record on table ActionPlanResponsible is created correctly but when I try to add a new ActionPlan with existent Responsible , the record in table ActionPlanResponsible is not created.

I passing ActionPlan and Responsible inside a Json that way:

{

"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"
}]

That is the way I'm doing the request in EF...

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

context.ActionPlan.Add(actionPlan); 

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

The ActionPlan entity:

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

The Responsible entity:

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

You also have to add the Responsibles to actionPlan.Responsibles :

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

context.ActionPlan.Add(actionPlan); 

This doesn't create new Responsibles but established the associations, so EF knows it should insert join records.

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