【问题标题】:SaveChangesAsync() is hanging in EF Core 3.1SaveChangesAsync() 挂在 EF Core 3.1 中
【发布时间】:2019-12-20 23:52:31
【问题描述】:

VS 2019 ASP.NET Core 3.1 EF Core 3.1 Web API

我的 SQL 数据库中有以下表结构:

我允许用户“编辑”模板(更改操作/组)。当他们保存时,我删除了模板的所有子级并重新添加新的子级(在 DTO 类中传递)。代码是:

   var now = DateTime.UtcNow;

    var template = await _context.Template
        .Include(t => t.TemplateCell)
        .Include(t => t.TemplateGroup)
        .ThenInclude(t => t.TemplateCell)
        .Include(t => t.TemplateAction)
        .ThenInclude(t => t.TemplateCell)
        .FirstOrDefaultAsync(t => t.Id == dto.Id);

    // Updates the templates details
    template.Name = dto.Name;
    template.Description = dto.Description;
    template.InitialRisk = dto.InitialRisk;
    template.ModifiedWhen = now;
    template.ModifiedByUserId = user.Id;

    // Clear the old children
    template.TemplateCell
        .Clear();
    template.TemplateAction
        .Clear();
    template.TemplateGroup
        .Clear();

    // Add the new children
    int sortOrder = 0;
    foreach (var groupName in dto.GroupNames)
    {
        template.TemplateGroup
            .Add(new TemplateGroup
            {
                Name = groupName,
                SortOrder = sortOrder++
            });
    }

    sortOrder = 0;
    foreach (var actionName in dto.ActionNames)
    {
        template.TemplateAction
            .Add(new TemplateAction
            {
                Name = actionName,
                SortOrder = sortOrder++
            });
    }

    int cellIndex = 0;
    foreach (var group in template.TemplateGroup)
        foreach (var action in template.TemplateAction)
            template.TemplateCell
                 .Add(new TemplateCell
                 {
                     TemplateGroup = group,
                     TemplateAction = action,
                     IsEnabled = dto.Cells[cellIndex++]
                 });

    await _context.SaveChangesAsync();  // Does not seem to ever return from here?

    return template.Id;

它一直在等待 _context.SaveChangesAsync() 并且似乎永远不会从该方法返回。 SQL Profiler 未显示任何活动。

任何人都可以看到可能导致问题的原因吗?

【问题讨论】:

    标签: asp.net-core entity-framework-core


    【解决方案1】:

    我设法让它工作,但不知道为什么我必须“两次”删除东西......

        _context.TemplateCell.RemoveRange(template.TemplateCell);
        _context.TemplateAction.RemoveRange(template.TemplateAction);
        _context.TemplateGroup.RemoveRange(template.TemplateGroup);
    
        template.TemplateCell
            .Clear();
        template.TemplateAction
            .Clear();
        template.TemplateGroup
            .Clear();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2021-08-09
      • 2022-11-11
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多