开发者

Adding object to navigation property collection creates new entity

I am using Entity Framework 4.

I am trying to associate a new entity with an existing entity. The system ends up creating a new child entity when in fact I just want to add a referen开发者_开发百科ce to the child object to the parent.

There is a many to many relationship between the two entities so I cannot simply set the FK property of the parent entity. I have tried parent.ChildCollection.Add(child) which simply creates a new child object in the database. This is what I am trying to avoid.

I must be doing something obviously wrong.

thanks

updated code sample

Code sample for my Self-Tracking-Entities that I have to do client side Right now I have something like this to get all children from server then loop through to find the one i want, then add it to the object collection

          List<Service.Child> childs = _client.GetChildren();

I have to loop through that collection to find the right one to add to the parent.childs collection ie.

            List<Service.Child> childList = new List<Service.Child>();
            foreach (Service.Child child in childList) {
                if (child.ChildId == childId)
                    childList.Add(child);
            }
            contact.Childs = childList;


If an entity originally came from the database and has its own EntityKey properties populated, using Add to link it to another entity will change its EntityState to Added. Even though it is a preexisting entity, SaveChanges will create an insert command for this entity. You should consider using Attach instead:

parent.ChildCollection.Attach(child);

Using the Attach method, you can define relationships between entities that already exist in the ObjectContext but that have not been connected automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜