Question

My question evolves around best practice.

Right now im using entity framework with ASP.NET and would like it top performance.

Would you generally check in the database for a existing record before adding one, or would you rely on the exception being throw or even expect that the parameters given are relevant and active.

Example: (ASP.NET with Identity)

public ResultWrapper AddUserToRole(string user, bool userId, string role, bool roleId)
{
    ApplicationUser appUser = FindUser(user, userId);
    ApplicationRole appRole = FindRole(role, roleId);

    if (appUser == null || appRole == null)
        return new ResultWrapper(false, "Unknown user or role");
    else
    {
        IdentityResult result = userManager.AddToRole(appUser.Id, appRole.Name);
        db.SaveChanges(); // AutoSaveChanges is false, so update.
        return new ResultWrapper(result.Succeeded, result.Errors);
    }
}
Was it helpful?

Solution

Besides being a very opinion based question, I think there are appropriate guidelines one can follow.

Would you generally check in the database for a existing record before adding one, or would you rely on the exception being throw or even expect that the parameters given are relevant and active.

This completely depends on context in my opinion.

For extremely high transactions, I would write a stored procedure.

Otherwise it depends on the concurrency of the operation, and in this particular instance, I don't think multiple people are going to try to add the same person to the same role, so exceptions are minimized and acceptable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top