Last active
March 19, 2017 09:19
-
-
Save tayyebi/f2f99d5b29105d7d048789494ae9f0c5 to your computer and use it in GitHub Desktop.
Validate any entity framework model from any .NET program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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