EF核心保存更改不适用于删除

问题描述 投票:0回答:1

我正在尝试从我的域中删除子项,但是Savechanges()无法正常工作,并且没有发生异常,我正在Dbcontext中跟踪并找到状态已更改的实体。添加或更新工作正常。在添加IEventbus接口以发布事件之前,一切正常。我在域类中的删除方法。

 public void RemoveItem(Guid id, IEventBus eventBus)
    {
        if (!string.IsNullOrWhiteSpace(this.Confirmer.UserId))
        {
            throw new RemoveItemOfConfirmedScrapException();
        }

        var scrapItem = this.ScrapItems.First(p => p.Id == id);

        var assetId = scrapItem.AssetId;


        this.ScrapItems.Remove(this.ScrapItems.First(p => p.Id == id));


          eventBus.Publish(new ScrapItemRemovedEvent(assetId));
    }

这是我要保存在数据库中的UnitOfWork。

 public class UnitOfWork : IUnitWork
{
    private readonly IDbContext dbContext;

    private DbContextBase dbContextBase;
    public UnitOfWork(IDbContext dbContext)
    {
        this.dbContext = dbContext;

        this.dbContextBase = dbContext as DbContextBase;
    }

    public void Commit()
    {
        try
        {
            this.dbContext.SaveChanges();
        }
        catch
        {

            RollBack();
            throw;
        }

    }
    public void RollBack()
    {
        this.dbContextBase.ChangeTracker.Entries()
            .Where(e => e.Entity != null).ToList()
            .ForEach(e => e.State = EntityState.Detached);
    }
}

该删除发生了什么事情,即使在父实体中也可以在其他域中使用,但在这种情况下,在数据库中无法删除。并且ChangeTracker显示特定实体状态已更改为“已修改”,但没有任何异常完成作业并且未对数据库产生影响。

c# entity-framework entity-framework-core domain-driven-design savechanges
1个回答
0
投票
    var scrapItem = this.ScrapItems.First(p => p.Id == id);
    var assetId = scrapItem.AssetId;
    this.ScrapItems.Remove(scrapItem);
    this.Commit(); // you weren't committing before
© www.soinside.com 2019 - 2024. All rights reserved.