For my EF (Entity Framework 4.1) I was using POCO templates to generate DTOs.
POCO are very simple objects but I did want to separate my MVC UI from Entity Framework dependency, so I”ve used a wrapper classes for my POCO classes from EF.
Something like this, where Medication would be a POCO templated class from EF and MedicationModel is a wrapper.
public class MedicationModel:Mediation{
………………..
}
Another approach could be a total encapsulation of Medication class, but… I did it this way.
Well so far so good, but the question was how to convert and/or assign data to a simple entity to persist it in DB?
My solution in this case was simple. I created an extension for my classes.
All of my extensions would implement one method on the common static extension class:
Snippet from the extension class.
public static List<AppointmentForm> ToAppointmentFormList(this ICollection<AppointmentFormModel> forms) {
List<AppointmentForm> list = new List<AppointmentForm>();
foreach (var f in forms) {
list.Add(f.ToAppointmentForm());
}
return list;
}
#region - Base function for Objects conversions -
private static void To<F, T>(F from, ref T to) {
ExtentionBase.To<F, T>(from, ref to);
}
#endregion - Base function for Objects conversions -
The base Generic method looks like this:
public static class ExtentionBase {
#region - Base function for Objects conversions -
public static void To<F, T>(F from, ref T to) {
if (from != null) {
Type fromType = from.GetType();
Type toType = to.GetType();
PropertyInfo[] fromPropertyInfo = fromType.GetProperties();
PropertyInfo[] toPropertyInfo = toType.GetProperties();
foreach (var prop in fromPropertyInfo) {
var targetProperty = toType.GetProperty(prop.Name);
if (targetProperty != null && targetProperty.CanWrite) {
try {
var value = prop.GetValue(from, null);
if (value != null && (value.GetType().BaseType.Name.ToString().Equals("ValueType") ||
value.GetType().BaseType.Name.ToString().Equals("Object") ||
value.GetType().BaseType.Name.ToString().Equals("RelatedEnd"))
) {
targetProperty.SetValue(to, value, null);
}
} catch {
Console.Out.WriteLine("Error");
}
}
}
}
}
#endregion - Base function for Objects conversions -
}
To get the source code goto: http://clires3.codeplex.com
To see the app demo goto http://clires.tateeda.com