Tuesday 4 April 2017

Using Automapper to upload file from HttpPostedFile to entity File

If you are using Automapper, this is how to upload a file from input type file (HttpPostedFile) to domain entity (File). This is also updating existing entity if exist.

public static void Initialize()
{
    Mapper.Initialize(cfg =>
     {
      cfg.CreateMap<HttpPostedFileBase, File>().
         ConvertUsing((source, dest) =>
         {
          File result = dest ?? new File();
          if (source != null)
          {
              result.FileName = System.IO.Path.GetFileName(source.FileName);
              result.ContentType = source.ContentType;
              using (var reader = new System.IO.BinaryReader(source.InputStream))
               result.FileContent = reader.ReadBytes(source.ContentLength);
          }
          return result;
         });
     });
#if DEBUG
    Mapper.AssertConfigurationIsValid();
#endif
}

As you can see I use ConvertUsing, because I could built entirely new object or update existing destination (the dest variable). ConvertUsing also ignore validation of those type. This is the domain entity File definition.


    public class File
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string FileName { get; set; }

        [Required]
        [Column(TypeName = "varbinary(max)")]
        public byte[] FileContent { get; set; }

        public string ContentType { get; set; }

    }

And last thing, you need to call mapper using theirs method and not the property. Property will return a new entity, and method return existing one so it can be used to update EF domain.

I was using Automapper version 6.0.2 in an ASP.Net MVC project with code first Entity Framework 6.