Skip to content

Instantly share code, notes, and snippets.

@odytrice odytrice/Extensions.cs
Last active Sep 28, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.