我有这种情况: 我有一个拥有多个目标的MasterPlanComponent对象。 这些目标有多个目标。
创建一个masterPlanComponent(具有2个目标)后,我们为这两个目标都创建了4个目标。
这应该是这样的:
以下代码的问题在于,仅创建了一组四个目标,并且仅用于第二个目标。
public async Task<MasterPlanComponent> CreateMasterPlanComponent(int masterPlanId, CreateMasterPlanComponentCommand command)
{
var masterPlan = await _context.MasterPlans
.Include(mp => mp.Components)
.Include(mp => mp.Objectives)
.SingleOrDefaultAsync(m => m.MasterPlanId == masterPlanId);
var targets = new List<ObjectiveNetTarget>();
//creating new targets and setting two of their fields
for (int i = 0 ; i < 4 ; i++)
{
targets.Add(new ObjectiveNetTarget
{
CustomerMarketSegment = command.Scope.CustomerMarketSegment,
OrganizationUnit = new OrganizationUnitRef
{
Name = "Sales",
Code = "1251"
}
});
}
var masterPlanComponent = Mapper.Map<CreateMasterPlanComponentCommand, MasterPlanComponent>(command);
foreach (var objective in masterPlanComponent.Objectives)
{
objective.TargetValues = new List<ObjectiveNetTarget>(targets);
}
masterPlanComponent.Status = MasterPlanComponentStatuses.New;
masterPlan.Components.Add(masterPlanComponent);
masterPlan.Objectives = masterPlan.Objectives.Concat(masterPlanComponent.Objectives).ToList();
//masterPlanComponent.Objectives targets, I can see that both of them have 4 net targets as it should be
await _context.SaveChangesAsync();
_logger.LogInformation("New master plan component created.");
_logger.LogInformation("Master plan component id: " + masterPlanComponent.ComponentId.ToString());
//after I try to save the context however, only one of them has it.
return masterPlanComponent;
}
此代码仅将4个目标写入数据库 他们每个人只指向一个目标(最后一个)
答案 0 :(得分:1)
这听起来像是由于您要提前创建目标,然后将它们传递给每个目标而引起的。当您将创建的目标传递给第一个目标时,EF开始跟踪它们并将其标记为要插入。当您将相同的csharp对象通过ref传递给第二个目标时,它们已被标记为要插入,并且只需更新为引用第二个目标即可,而不是第一个。
尝试在csharp中为每个目标创建新的目标对象。 EF只会插入1行:1个csharp对象引用。