0

I am using mediator pattern (specifically MediatR) to grab an object (let's call it and Order) that I want to update with EFCore. However, it's like the item (Order) loses its tracking because it isn't updated.

I want to do it like so:

public class MyClass
{
    private readonly MyDbContext dbContext;
    private readonly IMediator mediator;

    public MyClass(MyDbContext dbContext, IMediator mediator) 
    {
        this.dbContext = dbContext;
        this.mediator = mediator;
    }

    protected void UpdateField() 
    {
        var order = await mediator.Send(new GetOrderByIdQuery(OrderId));

        order.PaymentId = newPaymentId;
        dbContext.SaveChanges();
    }
}

The above will not work and I have to do something like

protected void UpdateField() 
{
    var order = dbContext.Orders.SingleOrDefault(o => o.OrderId == OrderId);

    order.PaymentId = newPaymentId;
    dbContext.SaveChanges();
}

For it to work and save the new value like I want.

In this case, the GetOrderByIdQuery doesn't do anything fancy. It simply retrieves the order.

public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdQuery, Order>
{
    private readonly MyDbContext dbContext;

    public GetSubmissionByIdQueryHandler(MyDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public async Task<Order> Handle(GetOrderByIdQuery request, CancellationToken cancellationToken)
    {
        return (await dbContext.Orders.FindAsync(request.OrderId));
    }
}

And for completeness, here is the Order class

public class Order
{
    public Guid OrderId { get; private set; }
    public string PaymentId { get; set; }
}
thalacker
  • 2,389
  • 3
  • 23
  • 44
  • 2
    How did you register the DbContext to the DI Container? If you use EF's `AddDbContext` with the default options, this should not happen – Gur Galler Mar 27 '20 at 18:26
  • hmm.. that very well could be part of the issue. I will look into that! – thalacker Mar 27 '20 at 19:10
  • @GurGaller you were spot on. That was the issue. I had some other things set up for my DbContext injection but they weren't quite right. I added that, and it worked like a charm. If you post an answer, I'll mark it. – thalacker Mar 27 '20 at 19:33

0 Answers0