C
C#7mo ago
mikibanan

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?
public async Task UpdateAsync(Order updatedOrder)
{

var order = await dbContext.Orders
.Include(order => order.OrderDates)
.Include(order => order.OrderPositions)
.FirstOrDefaultAsync(x => x.OrderId == updatedOrder.OrderId)
?? throw new DbException("Order not found!");

await dbContext.Entry(order).ReloadAsync();

if (updatedOrder.IsFinalized) throw new DbException("Cannot update finalized updatedOrder!");

updatedOrder.DraftModificationDate = DateTime.Now;

dbContext.Entry(updatedOrder).State = EntityState.Modified;

try
{
await dbContext.SaveChangesAsync();
}
catch (Exception e)
{
throw new DbException("Cannot update updatedOrder!", e);
}
}
public async Task UpdateAsync(Order updatedOrder)
{

var order = await dbContext.Orders
.Include(order => order.OrderDates)
.Include(order => order.OrderPositions)
.FirstOrDefaultAsync(x => x.OrderId == updatedOrder.OrderId)
?? throw new DbException("Order not found!");

await dbContext.Entry(order).ReloadAsync();

if (updatedOrder.IsFinalized) throw new DbException("Cannot update finalized updatedOrder!");

updatedOrder.DraftModificationDate = DateTime.Now;

dbContext.Entry(updatedOrder).State = EntityState.Modified;

try
{
await dbContext.SaveChangesAsync();
}
catch (Exception e)
{
throw new DbException("Cannot update updatedOrder!", e);
}
}
I tried doing something like this, but the order is not updating.
15 Replies
mikibanan
mikibanan7mo ago
Order is refreshing but it does not update Becuase I suppose it is updated with the data loaded from db
Keswiik
Keswiik7mo ago
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.
Jimmacle
Jimmacle7mo ago
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
Keswiik
Keswiik7mo ago
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)
mikibanan
mikibanan7mo ago
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
Jimmacle
Jimmacle7mo ago
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
mikibanan
mikibanan7mo ago
I have the lifetime oof the context set to scoped, so it's known blazor's bug
Jimmacle
Jimmacle7mo ago
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
mikibanan
mikibanan7mo ago
Yes but the fact that AddDbContext results in unexpected behaviour in Blazor for me sounds like a bug
Jimmacle
Jimmacle7mo ago
it sounds like a bug if you haven't researched how blazor server works
mikibanan
mikibanan7mo ago
I'll try this ContextFactory
Jimmacle
Jimmacle7mo ago
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
mikibanan
mikibanan7mo ago
So do I, it's a call from the repository What is mediatr?
Jimmacle
Jimmacle7mo ago
GitHub
GitHub - jbogard/MediatR: Simple, unambitious mediator implementati...
Simple, unambitious mediator implementation in .NET - GitHub - jbogard/MediatR: Simple, unambitious mediator implementation in .NET
Jimmacle
Jimmacle7mo ago
it's not directly applicable to your problem this is the main bit of how i work around blazor scoping issues
public async Task<T> Send<T>(IRequest<T> request)
{
using var scope = await CreateScope();
return await scope.ServiceProvider.GetRequiredService<IMediator>().Send(request);
}

private async Task<IServiceScope> CreateScope()
{
var scope = _scopeFactory.CreateScope();
var authState = await _authState.GetAuthenticationStateAsync();
scope.ServiceProvider.GetRequiredService<CurrentUserService>().User = authState.User;
return scope;
}
public async Task<T> Send<T>(IRequest<T> request)
{
using var scope = await CreateScope();
return await scope.ServiceProvider.GetRequiredService<IMediator>().Send(request);
}

private async Task<IServiceScope> CreateScope()
{
var scope = _scopeFactory.CreateScope();
var authState = await _authState.GetAuthenticationStateAsync();
scope.ServiceProvider.GetRequiredService<CurrentUserService>().User = authState.User;
return scope;
}
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
Want results from more Discord servers?
Add your server
More Posts
How to make an image bounce around the screen like a screensaver?I'm trying to make a program for a friend which has an image that moves around the screen and bounceNotifyIcon reference in Wpf doesn't workI am having problems with this code. I think I have the correct usings but the NotifyIcon is still nWhat's the proper way to build source generator?## Problem I've just started my source generator with minimal example. When I made change to `C.TexKestrel not returning full certificate chain .NET 6Hi all 👋 TL;DR **It looks Kestrel doesn't return the full certificate chain in .NET 6** I have a how to test untestable codehello there before reaching 100% coverage theres a single seemingly untestable line of code can soEF Core TPC Inheritance strategy - Select query to include individual navigational propertyHello, I have 2 similar entities, which are derived from a base class. The base class is `Animal`, Anyway to make code that knows a call has gone to voicemailI'm using 3cx dialer and there is no way to do that, If you know any way on doing this please help mWhy does my very simple C# program leak 890MB of RAM?I'm writing a very simple C# application that downloads dummy data from URLs to test internet speed,Hello! i am new to c # what editor should i use?i normally use visual studio code but i get reccomended to use jetbrains rider for c sharp which do Automate creation of XSD during buildHi, I have a data model in an assembly used to read program configuration. I would like to generate