1.6.4. Data Transfer Object

  • To seperate domain models and conroller

  • 1.Create a new folder whichh is called DTO

  • 2.Create DTO object to DTO folder

      public class CustomerDto
      {
          public int Id { get; set; }
    
          [Required]
          [StringLength(255)]
          public string Name { get; set; }
    
          public bool IsSubscribeToNesletter { get; set; }
    
          public byte membershipTypeId { get; set; }
    
          [Min18YearsIfAMember]
          public string Birthday { get; set; }
      }
  • 3.Install automapper:

    • nuget console:

        install-package automapper -version:4.1
  • 4.Add a profile class (MappingProfile.cs) in App_start folder:

    namespace Vidly2.App_Start
    {
      public class MappingProfile: Profile
      {
          public MappingProfile()
          {
              Mapper.CreateMap<Customer, CustomerDto>();
              Mapper.CreateMap<CustomerDto, Customer>();
          }
      }
    }
  • 5.Edit Clobal.asax.cs:

      public class MvcApplication : System.Web.HttpApplication
      {
          protected void Application_Start()
          {
              Mapper.Initialize(c => c.AddProfile<MappingProfile>());
              GlobalConfiguration.Configure(WebApiConfig.Register);
              AreaRegistration.RegisterAllAreas();
              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
              RouteConfig.RegisterRoutes(RouteTable.Routes);
              BundleConfig.RegisterBundles(BundleTable.Bundles);
          }
      }
  • 6.Modify controller:

      public class CustomersController : ApiController
      {
          private ApplicationDbContext _context;
    
          public CustomersController()
          {
              _context = new ApplicationDbContext();
          }
    
          // GET /api/customers
          [HttpGet]
          public IEnumerable<CustomerDto> GetCustomers()
          {
              return _context.Customers.ToList().Select(Mapper.Map<Customer, CustomerDto>);
          }
    
          // GET /api/customers/1
          public CustomerDto GetCustomers(int id)
          {
              var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
    
              if (customer == null)
              {
                  throw new HttpResponseException(HttpStatusCode.NotFound);
              }
    
              return Mapper.Map<Customer, CustomerDto>(customer);
          }
    
          // POST /api/customers
          [HttpPost]
          public CustomerDto CreateCustomers(CustomerDto customerDto)
          {
              if (!ModelState.IsValid)
              {
                  throw new HttpResponseException(HttpStatusCode.BadRequest);
              }
              var customer = Mapper.Map<CustomerDto, Customer>(customerDto);
              _context.Customers.Add(customer);
              _context.SaveChanges();
              customerDto.Id = customer.Id;
              return customerDto;
          }
    
          // PUT /api/customers/1
          [HttpPut]
          public void UpdateCustomers(int id, CustomerDto customerDto)
          {
              if (!ModelState.IsValid)
              {
                  throw new HttpResponseException(HttpStatusCode.BadRequest);
              }
    
              var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
    
              if (customerInDb == null)
              {
                  throw new HttpResponseException(HttpStatusCode.NotFound);
              }
    
              Mapper.Map(customerDto, customerInDb);
    
              _context.SaveChanges();
          }
    
          // PUT /api/customers/1
          [HttpDelete]
          public void DeleteCustomers(int id)
          {
              var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
    
              if (customerInDb == null)
              {
                  throw new HttpResponseException(HttpStatusCode.NotFound);
              }
    
              _context.Customers.Remove(customerInDb);
              _context.SaveChanges();
          }
      }

Last updated