Multiplicity constraint violated. The role Child_P

2019-08-23 02:33发布

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.

1条回答
倾城 Initia
2楼-- · 2019-08-23 03:18

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

查看更多
登录 后发表回答