繁体   English   中英

EF 7 - 尽管存在值,但上下文返回 null

[英]EF 7 - Context returns null although values are there

我有一个 CQRS 设置,我正在尝试使用域事件。 收到新订单的命令后,我将新创建的Order object 添加到dbcontext中。

public async Task<Guid> Handle(CreateOrderCommand message, CancellationToken cancellationToken)
        {
            
            ...

            var order = new Order(...);

            ...

            order.SubmitOrder();

            _orderRepository.Add(order);

            await _orderRepository.UnitOfWork
                .SaveEntitiesAsync(cancellationToken);

            return order.Id;
        }

order.SubmitOrder()方法如下


public void SubmitOrder()
    {
        AddDomainEvent(new OrderPlacedDomainEvent(Guid.NewGuid(), Id));
    }

orderRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); 正在重载到UnitOfWork.SaveEntitiesAsync() ,如下所示:

 public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
    {
        // Dispatch Domain Events collection. 
        // Choices:
        // A) Right BEFORE committing data (EF SaveChanges) into the DB will make a single transaction including  
        // side effects from the domain event handlers which are using the same DbContext with "InstancePerLifetimeScope" or "scoped" lifetime
        // B) Right AFTER committing data (EF SaveChanges) into the DB will make multiple transactions. 
        // You will need to handle eventual consistency and compensatory actions in case of failures in any of the Handlers. 
        if (_mediator != null)
        {
            await _mediator.DispatchDomainEventsAsync(this);
        }

        // After executing this line all the changes (from the Command Handler and Domain Event Handlers) 
        // performed through the DbContext will be committed
        await base.SaveChangesAsync(cancellationToken);
        return true;
    }

请注意,在分派事件和调用处理程序之前不会保存更改。

现在在事件处理程序中,当我试图从上下文中获取订单 object 时:

await _context.Orders.Include(o => o.OrderItems).SingleOrDefaultAsync(o => o.Id == id, cancellationToken: cancellationToken);

它返回null尽管数据在_context.ChangeTracker.DebugView.LongView下的上下文中可用

在此处输入图像描述

有什么办法可以得到这里的order数据吗?

好吧,找到解决方案:

如果使用Find / FindAsync而不是SingleOrDefaultAsync ,它将返回更改跟踪器中可用的值。

public async Task<Order?> FindAsync(Guid id, CancellationToken cancellationToken = default)
        =>  await _context.Orders.FindAsync(new object[] { id }, cancellationToken: cancellationToken); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM