0

I did a lot of research but haven't found any answer that matches my problem. I even tried to use the The relationship could not be changed because one or more of the foreign-key properties is non-nullable example. No success.

I'm working with Entity Framework 6 Code First (Fluent API), POCO Classes.

I have a class called Parent and a class called Child

One Parent can have one or more Childs (one to many relationship)

So, in my ParentMapping class I did:

HasMany(p => p.Childs).WithRequired(p => p.Parent).Map(m => m.MapKey("ParentId"));

and in my ChildMapping class I did:

HasRequired(p => p.Parent).WithMany(p => p.Childs).Map(m => m.MapKey("ParentId"));

I persist (Insert, Update and Delete) my child poco class at the same time I persist the parent class. So every time I save my parent class, it has one or more child objects in its Childs property. Thus the parent object is responsible for persist its child objects.

I followed the example above (see the link) to save data into the database.

I get below message when I try to add a new child to the db existent Parent, which already has one child in the database, and call the db.SaveChanges:

Multiplicity constraint violated. The role Child_Parent_Target of the relationship Child_Parent has multiplicity 1 or 0..1.

Can anyone help me? I'm struggling with this and see no light in the end of the tunnel.

Community
  • 1
  • 1
Marco Alves
  • 2,776
  • 3
  • 23
  • 33
  • You really should show the code where this exception is raised. – Gert Arnold Jan 29 '14 at 08:40
  • 1
    @GertArnold I thank you for your comment. But I think I've explained everything clearly. Btw, I've answered the question and I really suggest you check it out. It's very instructive, from my point of view. Anyway, thank you again. – Marco Alves Jan 29 '14 at 12:39

1 Answers1

0

I was able to solve my problem using GraphDiff amazing library. It just does everything for us when talking about parent/child persisting.

Check it out at this post: GraphDiff - Allowing automated updates of a graph of detached entities

Community
  • 1
  • 1
Marco Alves
  • 2,776
  • 3
  • 23
  • 33