Introduction
Suppose you work with an ORM (e.g.:
Entity Framework) and you usually use DTO (Data Transfer Object) pattern to transfer data.
When creating a DTO class from a binding
table, you need most of mapped properties, so that you must define them again in
your new class. Also when you have to transfer object to a view, you need to bind
it with data base values.
If you want to avoid the tedious task of
fill object, you can use reflection or an IOC container as AutoMapper, but you
still need to declare all properties to object.
Using inheritance you won’t need it, but,
by default the class will be linked by Entity Framework to data context; also
since it’s a subclass it’s not possible to cast it from its parent class.
The solution is as follows:
- To declare an inherited class.
- To unmap class from Entity Framework by
using
NotMapped
keyword. - To bind properties through reflection
with its parent class.
Background
If you are going to use this code, it’s supposed you are programming with
C# and Entity Framework, as well as you have knowledge about DTO pattern and
reflection.
Using the Code
Your DTO Class:
[NotMapped]
public class YourDTO: YourDBContextClass
{
Public property string FullName { get{ return (Name + " " + Surname); } }
}
The Controller:
public ActionResult Print(int id)
{
DTO.YourDTO dtoObj = new DTO.YourDTO();
dtoObj.CopyObject(dbContext.ParentClass.First(l => l.id==id));
return (dtoObj);
}
The Reflection Method
CopyObject as an Extension Method
public static class ObjectExtensions
{
public static void CopyObject(this object objTo, object objFrom)
{
Type tObjFrom = objFrom.GetType();
Type tObjTo = objTo.GetType();
var listPropObj1 = tObjFrom.GetProperties().Where(p => p.GetValue(objFrom) != null).ToList();
foreach (var item in listPropObj1){
if (tObjTo.GetProperty(item.Name) != null){
tObjTo.GetProperty(item.Name).SetValue(objTo, item.GetValue(objFrom));
}
}
}
}