You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中调用AddAsync保存修改无效且代码跳过的问题求助

问题分析与修复方案

核心问题拆解

  1. AddAsync代码跳过:大概率是底层异步方法实现不规范(比如同步逻辑包装成空异步),或是未触发实际的异步执行流程;
  2. 修改无法保存:EF Core(或类似ORM)中添加实体后必须调用SaveChangesAsync才能将变更提交到数据库,你的代码缺少这一步关键操作。

具体修复步骤

1. 恢复并完善AppService的保存逻辑

取消AppServiceProfileTraceClass中SaveChangesAsync的注释,确保它能调用底层服务的保存方法:

public class AppServiceProfileTraceClass : AppServiceBase<ProfileTraceClass>, IAppServiceProfileTraceClass
{
    public AppServiceProfileTraceClass(IServiceProfileTraceClass service) : base(service) { }
    
    public async Task<int> SaveChangesAsync()
    {
        return await _service.SaveChangesAsync();
    }
}

同步更新接口定义:

public interface IAppServiceProfileTraceClass : IAppServiceBase<ProfileTraceClass>
{
    Task<int> SaveChangesAsync();
}

2. 在控制器中添加提交操作

在循环添加实体后调用SaveChangesAsync,确保所有变更持久化到数据库,同时修正ViewBag不可靠的问题:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(int id, IEnumerable<ModelProfileTraceClass> model)
{
    try
    {
        var selectedClasses = model.Where(m => m.IsSelected).ToList();
        var obj = Mapper.Map<IEnumerable<ProfileTraceClass>>(selectedClasses);

        foreach (var objs in obj)
        {
            await _appServiceProfileTraceClass.AddAsync(objs).ConfigureAwait(false);
        }
        // 新增:提交所有变更到数据库
        await _appServiceProfileTraceClass.SaveChangesAsync().ConfigureAwait(false);
        
        return RedirectToAction("Index", "DB2ProfileTraceType", new { id = id });
    }
    catch (Exception ex)
    {
        ViewBag.ErrorMessage = ex.ToString(); // 输出完整异常信息便于排查
        return View(model);
    }
}

3. 检查底层AddAsync实现

确保AppServiceBase中的AddAsync是真正的异步逻辑:

public abstract class AppServiceBase<TEntity>
{
    protected readonly IServiceBase<TEntity> _service;

    public AppServiceBase(IServiceBase<TEntity> service)
    {
        _service = service;
    }

    public virtual async Task AddAsync(TEntity entity)
    {
        await _service.AddAsync(entity).ConfigureAwait(false);
    }
}

同时确认ServiceProfileTraceClass的实现正确:

public class ServiceProfileTraceClass : IServiceProfileTraceClass
{
    private readonly DbContext _context;

    public ServiceProfileTraceClass(DbContext context)
    {
        _context = context;
    }

    public async Task AddAsync(ProfileTraceClass entity)
    {
        await _context.Set<ProfileTraceClass>().AddAsync(entity).ConfigureAwait(false);
    }

    public async Task<int> SaveChangesAsync()
    {
        return await _context.SaveChangesAsync().ConfigureAwait(false);
    }
}

4. 避免重复添加实体

因为Edit方法是维护关联关系,建议添加前检查是否已存在该关联,防止重复插入:

foreach (var objs in obj)
{
    var exists = await _appServiceProfileTraceClass
        .GetAll()
        .AnyAsync(x => x.ProfileTraceId == id && x.TraceClassId == objs.TraceClassId)
        .ConfigureAwait(false);
    if (!exists)
    {
        await _appServiceProfileTraceClass.AddAsync(objs).ConfigureAwait(false);
    }
}

调试建议

  • 在AddAsync和SaveChangesAsync方法中设置断点,确认代码是否实际执行;
  • 捕获完整异常信息(ex.ToString()),排查是否有隐藏的数据库约束异常或映射错误。

内容的提问来源于stack exchange,提问作者Bizzle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 23:10:04