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 to 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?