为什么这个实体框架例程会跳过某些孩子的插入?

时间:2018-04-10 00:31:54

标签: c# .net entity-framework

我有以下方法在ADGroup中插入一行,然后在子表GroupExtension中插入一行:

    public async Task AddADGroupsAsync(List<ADGroup> adGroups)
    {
        await Task.Run(async () =>
        {
            EntityFramework.ADGroup dbADGroup;
            EntityFramework.ADGroup dbADGroupInsert;
            GroupExtension dbGroupExtension;

            using (var dbContext = new SecurityAPIEntities())
            {
                foreach (var adGroup in adGroups)
                {
                    dbADGroup = new EntityFramework.ADGroup
                    {
                        Id = Guid.NewGuid(),
                        Name = adGroup.Guid
                    };

                    dbADGroupInsert = dbContext.ADGroups.Add(dbADGroup);
                    dbGroupExtension = new GroupExtension
                    {
                        Id = Guid.NewGuid(),
                        CreatedDateTime = DateTime.Now,
                        UpdatedDateTime = DateTime.Now
                    };
                    dbADGroupInsert.GroupExtensions.Add(dbGroupExtension);
                }
                await dbContext.SaveChangesAsync();
            }
        });
    }

问题是此代码在ADGroup中插入了8914行,而在GroupExtension中只插入了8676行。这似乎是一个非常基本的操作,所以我不确定为什么它会在少量子插入上失败。我认为当我在foreach循环中使用SaveChangesAsync()而不是在其后面时,此代码可能已经正常工作。

0 个答案:

没有答案