In this post we are going to see how to create a mapping between the two different models using automapper and copy the data from one model to another model.
First we have to install the automapper using Nuget.
Create models
Create a Profile for the mappings
then create a configuration class
Invoke the configuration class in startup.cs
use the configuration to copy the value from one model to another
From this post you can learn how to create a model mappings using automapper
First we have to install the automapper using Nuget.
Create models
public class PostViewModel
{
public HttpPostedFileBase File { set; get; }
public string PostTitle { set; get; }
public string PostDescription { set; get; }
}
public class PostModel
{
public string Title { set; get; }
public string Description { set; get; }
public string Details
{
get { return string.Format("{0},{1}", Title,
Description.Substring(10) + "..."); }
}
public string imageUrl { set; get; }
}
Create a Profile for the mappings
public class PostToViewModelMappingProfile:Profile
{
public override string ProfileName
{
get
{
return "PostToViewModelMapping";
}
}
protected override void Configure()
{
this.CreateMap<PostViewModel, PostModel>()
.ForMember(p => p.Title, pvm => pvm.MapFrom(vm => vm.PostTitle))
.ForMember(p => p.Description, pvm => pvm.MapFrom(vm => vm.PostDescription));
}
}
then create a configuration class
public class AutoMapperConfiguration
{
public static void Configure()
{
AutoMapper.Mapper.Initialize(cf => {
cf.AddProfile<PostToViewModelMappingProfile>();
});
}
}
Invoke the configuration class in startup.cs
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
AutoMapperConfiguration.Configure();
}
}
public ActionResult Upload(PostViewModel model)
{
var postmodel = Mapper.Map<PostViewModel, PostModel>(model);
postmodel.imageUrl = filename;
return View(postmodel);
}
From this post you can learn how to create a model mappings using automapper
No comments:
Post a Comment