C
C#5d ago
workani

✅ Implementing delete repository method & controller | Web Api

I would love to know how to properly implement delete repository method, in particularly how to handle possible null values.
16 Replies
Sehra
Sehra5d ago
$details
MODiX
MODiX5d ago
When you ask a question, make sure you include as much detail as possible. Such as code, the issue you are facing, what you expect the result to be, what .NET version you are using and what platform/environment (if any) are relevant to your question. Upload code here https://paste.mod.gg/, save, and copy the link into chat for others to see your shared code! (see $code for more information on how to paste your code)
Pobiega
Pobiega5d ago
In the simplest case, trying to delete something that doesnt exist isn't actually an error, as the end result is the same: the item doesn't exist. So if you are trying to write idempotent code, if the query doesnt delete anything, thats fine.
workani
workaniOP5d ago
So this code is just about fine?
public async Task DeleteByIdAsync(int id)
{
var comment = await context.Comments.FindAsync(id);

context.Comments.Remove(comment!);

await context.SaveChangesAsync();
}
public async Task DeleteByIdAsync(int id)
{
var comment = await context.Comments.FindAsync(id);

context.Comments.Remove(comment!);

await context.SaveChangesAsync();
}
Angius
Angius5d ago
Or better,
public async Task DeleteByIdAsync(int id)
{
_ = await context.Comments
.Where(c => c.Id == id)
.ExecuteDeleteAsync();
}
public async Task DeleteByIdAsync(int id)
{
_ = await context.Comments
.Where(c => c.Id == id)
.ExecuteDeleteAsync();
}
Or better yet, don't use repositories
Pobiega
Pobiega5d ago
Absolutely not. save changes when nothing was done is silly. doing DbSet.Remove(null) is silly. if you know its null, just stop there. that said, ZZZZZZZZs code is much nicer and more performant its a single query, instead of two
workani
workaniOP5d ago
I like it
FusedQyou
FusedQyou5d ago
Not that the result value of SaveChangesAsync also indicates if something was deleted at all in this case I assume the same happends with ExecuteDeleteAsync
Angius
Angius5d ago
Ye
FusedQyou
FusedQyou5d ago
It returns rows modified, so anything above 0 means there were changes
Angius
Angius5d ago
It returns the amount of rows affected Same for .ExecuteUpdateAsync()
FusedQyou
FusedQyou5d ago
Yeah, affected is a better word
workani
workaniOP5d ago
Could you explain please meaning of '_ ='
Angius
Angius5d ago
A discard Could as well be
public async Task DeleteByIdAsync(int id)
{
await context.Comments
.Where(c => c.Id == id)
.ExecuteDeleteAsync();
}
public async Task DeleteByIdAsync(int id)
{
await context.Comments
.Where(c => c.Id == id)
.ExecuteDeleteAsync();
}
But using a discard explicitly states "I know this method returns something, but I don't care"
workani
workaniOP5d ago
Thanks
Angius
Angius5d ago
A matter of preference, really How explicit you want to be

Did you find this page helpful?