C#C
C#3y ago
S-IERRA

❔ EntityFramework Code cleanup

I have lots of controllers like this, is there anyway I could clean this up?

for one I don't want to be calling the firstordefaultasync each time I have an ID parameter possibly there is somew ay to implicitly convert it while carrying context for performance sake?

Also I was thinking of moving the logic to the Logic layer But I'm not sure how I'd do validation there and return it, for example. if a user has missing permissions
return Unauthorized();


    [HttpPost("{serverId:guid}/view-logs")]
    public async Task<IActionResult> ViewLogs([FromClaim(ChatClaims.UserId)] Guid userId, Guid serverId)
    {
        await using var context = ContextFactory.CreateDbContext();

        if (await context.Users.FirstOrDefaultAsync(x => x.Id == userId) is not { } user)
            return Unauthorized();
        
        if (await context.Servers.FirstOrDefaultAsync(x => x.Id == serverId) is not { } server)
            return Unauthorized();

        context.Servers.Remove(server);
        
        return Ok();
    }
    
    [HttpPost("{serverId:guid}/create-invite")]
    public async Task<IActionResult> CreateInvite([FromClaim(ChatClaims.UserId)] Guid userId, Guid serverId)
    {
        return Ok();
    }
Was this page helpful?