Skip to content

Instantly share code, notes, and snippets.

@tayyebi
Last active March 19, 2017 09:19
Show Gist options
  • Save tayyebi/f2f99d5b29105d7d048789494ae9f0c5 to your computer and use it in GitHub Desktop.
Save tayyebi/f2f99d5b29105d7d048789494ae9f0c5 to your computer and use it in GitHub Desktop.
Validate any entity framework model from any .NET program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module2_Hamedan_MohammadRezaTayyebi.Components
{
public class RexaValidation
{
[Serializable]
public class RexaException : Exception
{
public RexaException() { }
public RexaException(string message) : base(message) { }
}
public RexaValidation(object modelInstance)
{
var validationContext = new ValidationContext(modelInstance, null, null);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(modelInstance, validationContext, results, true))
{
// Its OK
}
else
{
string t = String.Empty;
foreach (var item in results)
{
t += "\r\n - " + item.ErrorMessage;
}
throw new RexaException(t);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment