views:

101

answers:

1

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?

+1  A: 

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.

VinayC
I dont want either objects tracked by the context, I want them detached from the context so they can be returned by the function with no ties. Another function will handle the attach when they need to be saved.
Carl
Using the .Add() method throws a different error;The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object.
Carl
If I understood you correctly, probably you want to build object graph at some layer (client) and then submit it to a service layer doing persistence. You should perhaps use POCO entities from EF4 - see this article(http://msdn.microsoft.com/en-us/magazine/ee335715.aspx) for choices available with POCO.
VinayC