My CheckModelValidation
method (that tests a single model) tests out fine in my unit test just by passing in the class model UserInsertModel
as an object but when I try to pass in a list of models to CheckModelListValidation
in my unit test, it tells me it's an unknown method
(because it doesn't like what I'm trying to pass in - which is a List<UserInsertModel>
).
Is there a better way to do this using generics (which I've just recently gotten into)?
public class ValidationManager
{
public static void CheckModelListValidation(List<object> model)
{
string errorMessages = "";
int iCnt = 0;
foreach (var u in model)
{
iCnt += 1;
string itemErrors = ValidateModel(u);
if (!string.IsNullOrEmpty(itemErrors))
{
errorMessages = string.Format("Item {0} errors: {1}", iCnt, itemErrors);
}
}
if (!string.IsNullOrEmpty(errorMessages))
{
throw new Exception(errorMessages);
}
}
public static void CheckModelValidation(object model)
{
string errorMessages = ValidateModel(model);
if (!string.IsNullOrEmpty(errorMessages))
{
throw new Exception(errorMessages);
}
}
private static string ValidateModel(object model)
{
string errorMessages = "";
List<ValidationResult> validationResults = new List<ValidationResult>();
ValidationContext valContext = new ValidationContext(model, null, null);
bool isValid = Validator.TryValidateObject(model, valContext, validationResults, true);
if (!isValid)
{
errorMessages= string.Format("Errors: {0}", String.Join("; ", validationResults.Select(v => v.ErrorMessage).ToArray()));
}
return errorMessages;
}
}
And here's my implementation:
UserInsertModel model = new UserInsertModel();
model.EmailAddress = "test";
List<UserInsertModel> models = new List<UserInsertModel>();
models.Add(model);
models.Add(model);
ValidationManager.CheckModelListValidation(models);
You can make your validation class generic:
public class ValidationManager<T>
{
// Change methods to accept T instead of object
public static void CheckModelListValidation(List<T> model)
{
//...
public static void CheckModelValidation(T model)
{
// etc
将方法的签名更改为:
public static void CheckModelListValidation<T>(List<T> model)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.