[英]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.