【发布时间】:2010-09-16 08:19:46
【问题描述】:
我有一个函数,我想返回一个新实体,其中已经附加了一些子实体。我不想做的是首先在数据库中创建它们。我只想创建一个新的实体实例,创建一些新的子实体并将它们添加到父实体,然后在函数中返回父实体。
我从这段代码开始;
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;
}
本质上,我正在创建一个新的事件实体,它可以具有关联的动作实体 - 然后尝试根据它们的类型加载一些动作并将动作实体附加到事件实体。当这行代码skeletonEvent.Actions.Attach(action);执行时抛出以下异常;
当与此相关端关联的源对象处于添加、删除或分离状态时,附加操作无效。使用 NoTracking 合并选项加载的对象始终是分离的。
我哪里错了?
【问题讨论】:
标签: c# .net entity-framework