C# 保存具有相同对象属性的多个对象

C# 保存具有相同对象属性的多个对象,c#,asp.net-core,.net-core,entity-framework-core,C#,Asp.net Core,.net Core,Entity Framework Core,我有这样的情况: 我有一个MasterPlanComponent对象,它包含多个目标。 这些目标包含多个目标 在创建具有2个目标的总体规划组件时,我们为这两个目标创建了4个目标 这就是它应该看起来的样子: 1个组件>2个目标>8个目标一个为4个,另一个为4个,目标为空,只需在数据库中创建即可 下面代码的问题是,只创建了一组4个目标,并且只针对第二个目标 public async Task<MasterPlanComponent> CreateMasterPlanComponent(i

我有这样的情况: 我有一个MasterPlanComponent对象,它包含多个目标。 这些目标包含多个目标

在创建具有2个目标的总体规划组件时,我们为这两个目标创建了4个目标

这就是它应该看起来的样子:

1个组件>2个目标>8个目标一个为4个,另一个为4个,目标为空,只需在数据库中创建即可 下面代码的问题是,只创建了一组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个目标
每个目标只指向最后一个目标

这听起来像是因为您提前创建了目标,然后将其传递给每个目标。当您将创建的目标传递给第一个目标时,EF开始跟踪它们并将其标记为要插入。当您通过引用将相同的csharp对象传递给第二个目标时,它们已标记为要插入,并且仅更新为引用第二个目标而不是第一个目标


尝试在csharp中为每个目标创建新的目标对象。EF将只插入1行:1个csharp对象引用。

我是否在masterPlanComponent中的每个var目标的这一行中不插入该行。目标{objective.TargetValues=new Listtargets;}?考虑到我的目标在本质上是相同的,唯一的区别是它们属于哪个目标,什么才是一种不丑陋的方式呢?@wonder Correct,你没有在新的列表中这样做。对列表的引用是新的,但内容引用了相同的4个目标对象。你可以使用一个局部函数来创建你的4个目标,这意味着这个方法是局部的,如果这是唯一使用它的地方的话。此本地函数可以返回新目标的新集合。然后,在每个目标上,您都可以使用objective.TargetValues=CreateTargets;你可以检查一下,这解释了为什么你的新列表不够,并可能给你一个如何继续的想法。