Asp.Net Programming Bad Practices


Do Not Do This

1. Do not write a function like this:

public asyn Task<bool> CheckSomething(int Id){
return await _context.MyModel.Any(a => a.Id == Id);
}

Reason: The above code will throw an exception if no result is found in the MyModel Table. If the table is empty, there will be an error. Diagnosing an issue becomes hard because the code is executing in a Task, AKA Async.

The other reason is if there is an error, let's say on the database side, or the Table Schema is missing some columns the C# code will not explicitly show you that the columns are missing unless you wrap the code in a Try-Catch block to capture the Exception.

I recommend to only using Try Catch Block when developing or using it graciously. 

Instead, do this:

public async Taskbool> CheckSomething(int Id){
//validate incoming parameter
//Base Case
if(Id == 0){
return false;
}
//Otherwise, continue
MyModel myModel = _context.MyModel.Where(a => a.Id == Id)?.FirstOrDefault();
return myModel is null ? false : true;
}


This way you are validating whether the incoming Id is equal to 0, if yes just return false, otherwise execute code.






© 2024 - ErnesTech - Privacy
E-Commerce Return Policy