Refresh object in EntityFramework
Hi, I have the situation where multiple users can work on the same order. There is a possibility that the order will be finalized and other user can still make changes, because I'm checking Order.IsFinalized, but it is not updated before. How do I refresh object with current data?
I tried doing something like this, but the order is not updating.
15 Replies
Order is refreshing but it does not update
Becuase I suppose it is updated with the data loaded from db
Shouldn't you be checking
order.IsFinalized
instead of updatedOrder.IsFinalized
? From the way this reads, updatedOrder
is the user-modified instance and order
is freshly loaded at the beginning of the method.what behavior are you expecting here?
should any changes after an order is finalized be rejected?
this doesn't seem like a problem of refreshing, but of rejecting the second request entirely because it's not valid behavior to modify a finalized order
It seems to me that they checked the wrong
Order
instance, assumed the data was stale, and then attempted to reload the entity as a fix (but that isn't working because they're still checking the wrong instance for the IsFinalized
flag)I mean the thing is that EntityFramework stores e.g. Orders DbSet and it is not updated. When I'm refreshing the DbContext it does not update, because it is updated from the database, so it is the same value
you shouldn't be using the same dbcontext instance for getting and saving in this instance IMO
those are 2 different logical requests
get order -> some indeterminate amount of editing time -> update order
I have the lifetime oof the context set to scoped, so it's known blazor's bug
it's not a bug
blazor server scopes last the whole lifetime of the signalr session
that's just how it works
you need to use IDbContextFactory
Yes but the fact that AddDbContext results in unexpected behaviour in Blazor for me sounds like a bug
it sounds like a bug if you haven't researched how blazor server works
I'll try this ContextFactory
it's either that or come up with some other system to create more realistic per-request scopes
i do that with mediatr and create a new service scope for each mediatr request
but i also don't touch the dbcontext directly from any blazor code
So do I, it's a call from the repository
What is mediatr?
GitHub
GitHub - jbogard/MediatR: Simple, unambitious mediator implementati...
Simple, unambitious mediator implementation in .NET - GitHub - jbogard/MediatR: Simple, unambitious mediator implementation in .NET
it's not directly applicable to your problem
this is the main bit of how i work around blazor scoping issues
yes
i make my own scopes with blackjack and hookers
in my specific use case it works fine™️
but i'm going to switch to a proper client+api eventually so there is a strict separation