[ACCEPTED]- Insert new object with existing object-entity-framework-4

Accepted answer
Score: 19

If you don't want insert objectB you must inform 5 EF about it. When you call context.objectAs.AddObject(obj) for objectA you are 4 saying: I want to insert objectA and all its dependencies. But obviously you don't want to 3 save dependecies so you must either:

  • Load objectB from DB before adding it to objectA. In such case EF will know that objectB is existing object and it will not insert it again.
  • Attach objectB to context before adding it to objectA. ObjectB will be handled as existing but unchanged.
  • Set the state of objectB after inserting objectA. You can do that by calling: context.ObjectStateManager.ChangeObjectState(objectB, EntityState.Unchanged)

Example 2 of the fist suggestion:

var id = objectB.Id;
objectA.myObjectB = context.ObjectBs.SingleOrDefault(o => o.Id == id);

Example of the second 1 suggestion:

objectA.myObjectB = objectB;

Example of the third suggestion:

objectA.myObjectB = objectB;
context.ObjectStateManager.ChangeObjectState(objectB, EntityState.Unchanged);
Score: 1

I suppose that problem in following row:

objectA.myObjectB = (objectB)cmbBObjects.selectedItem;

Because 7 of result (objectB)cmbBObjects.selectedItem detached from datacontext entity 6 framework create new instance. Instead this 5 you can:

1.Assign objectB id to objectA

var b = (objectB)cmbBObjects.selectedItem;
objectA.myObjectBId = b.Id;

2.Or 4 load objectB from dataContext and than assign 3 to objectA:

var b = (objectB)cmbBObjects.selectedItem;
var dcB = context.ObjectBs.Single(x=> x.Id == b.Id);
objectA.myObjectB = dcB;

Just try my suggestions and come 2 back with results, because i don't know 1 exactly.

Hope this help.

More Related questions