简体   繁体   English

实体框架:创建一个实体,附加子实体,做一些事情然后保留实体……如何?

[英]Entity Framework: Create an entity, attach child entities, do some stuff then persist entities… how?

I have aa 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. 本质上,我正在创建一个新的Event实体,该实体可以具有关联的Action实体-然后尝试根据其类型加载某些动作并将Action实体附加到Event实体。 When the line of code skeletonEvent.Actions.Attach(action); 当代码行中的skelenetEvent.Actions.Attach(动作); 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. 使用NoTracking合并选项加载的对象始终是分离的。

Where are am I going wrong? 我要去哪里错了?

Perhaps you should try using Add method instead of Attach. 也许您应该尝试使用Add方法而不是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. 您可能必须使用AddObject(或生成的AddToEvent)方法将Event对象添加到ObjectContext。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM