Skip to content

Instantly share code, notes, and snippets.

@odytrice
Last active September 28, 2019 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odytrice/72b1a229435ce9c48abff0210778c02f to your computer and use it in GitHub Desktop.
Save odytrice/72b1a229435ce9c48abff0210778c02f to your computer and use it in GitHub Desktop.
Generic Abstract Model

Model & Extensions

Model Class for Abstract Business Objects Extensions for Automapping Properties

public static class Extensions
{
public static T ParseEnum<T>(this string value) where T : struct
{
if (Enum.TryParse(value, true, out T enumobj))
{
return enumobj;
}
else
{
return default(T);
}
}
/// <summary>
/// Update properties with properties of the object Supplied (typically anonymous)
/// </summary>
/// <typeparam name="T">Type of Source Object</typeparam>
/// <param name="destination">Object whose property you want to update</param>
/// <param name="source">destination object (typically anonymous) you want to take values from</param>
/// <returns>Update reference to same Object</returns>
public static T Assign<T>(this T destination, object source, params string[] ignoredProperties)
{
if (ignoredProperties == null) ignoredProperties = new string[0];
if (destination != null && source != null)
{
var query = from sourceProperty in source.GetType().GetProperties()
join destProperty in destination.GetType().GetProperties()
on sourceProperty.Name.ToLower() equals destProperty.Name.ToLower() //Case Insensitive Match
where !ignoredProperties.Contains(sourceProperty.Name)
where destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType) //Properties can be Assigned
where destProperty.GetSetMethod() != null //Destination Property is not Readonly
select new { sourceProperty, destProperty };
foreach (var pair in query)
{
//Go ahead and Assign the value on the destination
pair.destProperty
.SetValue(destination,
value: pair.sourceProperty.GetValue(obj: source, index: new object[] { }),
index: new object[] { });
}
}
return destination;
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach(var item in source)
{
action(item);
}
}
}
public abstract class Model : IValidatableObject
{
public Operation<ValidationResult[]> Validate()
{
var errors = new List<ValidationResult>();
Validator.TryValidateObject(this, new ValidationContext(this, serviceProvider: null, items: null), errors, true);
return new Operation<ValidationResult[]>
{
Result = errors.ToArray(),
Succeeded = errors.Any() == false,
Message = errors.Any() ? errors.Select(e => e.ErrorMessage).Aggregate((ag, e) => ag + ", " + e) : ""
};
}
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errors = new List<ValidationResult>();
return errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment