I'm trying to Create user defined function that handling User tries to add a new user with a duplicate id
and I create this :
public class DuplicateIdException:Exception
{
public DuplicateIdException(String message) : base(message)
{
}
public override string Message => $" --- {base.Message} --- ";
}
public class TestDuplicateIdException
{
static void validate(List<Object> Users)
{
bool flag = false;
Type DataType = Users[0].GetType();
List<DataType> UsersConverter = Users.Cast<DataType>().ToList();
flag = UsersConverter.Any(x => x.Id == Id);
if (flag)
{
throw new DuplicateIdException("Sorry, You duplicate the Id");
}
}
}
I have many objects types and all of them have Id attribute in them, but when i call object.Id it gave an error and not working.. So how can i check them and complete the Exception ?
CodePudding user response:
You can create a base class for all classes that have id ,it can be an interface or base class if you need to.
public class EntityBase
{
public int Id { get; set; }
}
then inherit/implement it
public class Users : EntityBase
{
}
public class Order : EntityBase
{
}
then validate with the base class/interface
public class ValidateDuplidateId
{
static void Validate(IEnumerable<EntityBase> entities,int id)
{
if (entities.Any(x => x.Id == id))
throw new Exception("Duplicate Id Found");
}
}
i don't like this approach of throwing exceptions for handling business logic errors, a better approach for me will be something like this
public class Validator
{
public static bool IsDuplicateId(IEnumerable<EntityBase> entities,int id)
{
if (entities.Any(x => x.Id == id))
return true;
return false;
}
}
then i will add a generic operation result class to handle any type of objects
public class OperationReuslt<T>
{
public T Result { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
}
in my user service ( for example )
public class UserSerivce
{
public OperationReuslt<Users>AddUser(int id)
{
//replace this with data from your actual data source
List<Users> users = new List<Users>();
if(Validator.IsDuplicateId(users,id))
{
return new OperationReuslt<Users>
{
Success = false,
Message = "Duplicate UserId"
};
}
// else proceed
}
}
you can use this approach as it more readable and doesn't have a performance drawback as the throwing exception approach , but in the end it all depends on your case