Entity Framework: Create an entity, attach child entities, do some stuff then persist entities... how?
I have a a function that I want to return a new entity with some child entities already attached. What I dont want to do is create them in the database first. I just want to create an new instance of the entity, create some new child entities and add them to the parent entity before returning the parent entity in the function.
I started with this code;
public BusinessEntities.Event CreateEventWithDefaultActions(EventType eventType)
{
Facades.Event eventFacade = new Facades.Event();
IList<BusinessEntities.DefaultAction> defaultActions;
// new event
BusinessEntities.Event skeletonEvent = new BusinessEntities.Event();
skeletonEvent.EventType = eventType;
// load the default actions
defaultActions = eventFacade.LoadDefaultActionTypes(eventType);
// create a new action and attach to the event
foreach (BusinessEntities.DefaultAction defaultAction in defaultActions)
{
BusinessEntities.Action action = new BusinessEntities.Action();
if(!defaultAction.ActionTypeReference.IsLoaded)
defaultAction.ActionTypeReference.Load();
action.ActionType = defaultAction.ActionType;
skeletonEvent.Actions.Attach(action); // exception thrown
}
return skeletonEvent;
}
Essentially, I am creating a new Event entity, which can have associated Action entities - then trying to load some actions based on their type and attach the Action entities t开发者_高级运维o the Event entitiy. When the line of code skeletonEvent.Actions.Attach(action); is executed the following exception is thrown;
Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached.
Where are am I going wrong?
Perhaps you should try using Add method instead of Attach. Attach should be used when both entities are tracked by object context. You may have to add Event object to the ObjectContext using AddObject (or generated AddToEvent) method.
精彩评论