C
C#5mo ago
Core

✅ EF Best way to do UPDATE on entity

Hello, EF by default tracks entities. That means, if a property of an entity is modified, SaveChanges() will do the update. Now, I set new values for the properties in the business logic layer, and the repository layer is responsible for any DB operation. My current method looks like this.... Is there a clearer approach or leave this as it is?
c#
public async Task UpdateEntityAsync()
{
try
{
await _dbContext.SaveChangesAsync();
}
catch (Exception)
{
//
}
}
c#
public async Task UpdateEntityAsync()
{
try
{
await _dbContext.SaveChangesAsync();
}
catch (Exception)
{
//
}
}
17 Replies
Yawnder
Yawnder5mo ago
Just don't add any kind of repositories on top of your DbContext. Just let your service deal with the DbContext directly.
Core
CoreOP5mo ago
Well, there is a quite large 100 row+ complex query for cursor pagination + filtering. And the app is built with N-tier architecture
Yawnder
Yawnder5mo ago
What does that have to do with anything?
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
Core
CoreOP5mo ago
If the repository layer (the one wrapping the EF queries) is removed, then the code should go somewhere
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
Yawnder
Yawnder5mo ago
With repositories on top of EFC's repository (yes, EF/EFC already implement the Unit of Work and the Repositories), you lose key abilities like projection and dynamic filtering, unless you add in tons and tons of pass-through that you have to add in, with all the boilerplate that goes with it.
Core
CoreOP5mo ago
Yes, this is very true. Thanks for pointing it out
Yawnder
Yawnder5mo ago
Just so you know, a LOT of people make this mistake. I've done it too.
Core
CoreOP5mo ago
I have a middleware catching exceptions. Would it be reasonable for doing a similar solution for EF exceptions, so no try, catch blocks?
Yawnder
Yawnder5mo ago
Where I'm working at now, there is a senior dev that has been using .Net for almost 20 years now, and they still want to use repositories to wrap EF 😛
Core
CoreOP5mo ago
If not wrapping, should I put them in private methods inside the logic layer?
Yawnder
Yawnder5mo ago
This logic should generally be implemented at the service/logic level, since it's at that point that you know how to handle what. If you want, you can let some exceptions through, like the DbUpdateConcurrency exception, and have these handled by a middleware. I'm not certain of what specifically you're talking about, so it's hard to give an advice on that.
Core
CoreOP5mo ago
Thanks for clarifying this concept It helped a lot
Yawnder
Yawnder5mo ago
Great! Good luck! Gotta go to bed now 😛
Core
CoreOP5mo ago
$close
MODiX
MODiX5mo ago
If you have no further questions, please use /close to mark the forum thread as answered

Did you find this page helpful?