Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

DTO from Entity Framework Class

4.14/5 (8 votes)
11 Mar 2014CPOL1 min read 55.1K  
To inherit an Entity Framework class, to extend it, bind to data and unmap it from DBContext.

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:

  1. To declare an inherited class.
  2. To unmap class from Entity Framework by using NotMapped keyword.
  3. 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:

C#
[NotMapped]
public class YourDTO: YourDBContextClass
{
    //Feel free to add properties. EF Won’t try to bind it with database
    Public property string FullName { get{ return (Name + " " + Surname); } }
} 

The Controller:

C#
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

C#
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));
            }
        }
   }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)