Using Automapper with profile
Install it from nuget
Add Automapper Config
AutomapperConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using AutoMapper;
namespace UsingAutoMapper.App_Start
{
public class AutoMapperConfig
{
public static void Configure()
{
Assembly[] cabiAssemblies =
AppDomain.CurrentDomain.GetAssemblies()
.Where(x =>
x.FullName.ToLowerInvariant().StartsWith("UsingAutoMapper".ToLower())).ToArray();
Mapper.Initialize(cfg =>
cfg.AddProfiles(cabiAssemblies));
}
}
}
It will add assemblies which are started with a name UsingAutoMapper
to mapper profile. Which will automatically create a profile
object.
Add Calling code in Global.Asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using UsingAutoMapper.App_Start;
namespace UsingAutoMapper
{
public class MvcApplication :
System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperConfig.Configure();
}
}
}
Add profile to mapping
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using UsingAutoMapper.Models;
namespace UsingAutoMapper.Mapping
{
public class ScopeProfile : Profile
{
public ScopeProfile()
{
CreateMap<ScopeViewModel,
Scope>();
}
}
}
Code calling it.
private void UsingProfileMapping()
{
ScopeViewModel model = new ScopeViewModel()
{
ScopeId = 1,
ScopeName = "ScopeOne",
};
var sourceWithMapper =
Mapper.Map<Scope>(model);
}
Classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UsingAutoMapper.Models
{
public class Scope
{
public int ScopeId { get; set; }
public string ScopeName { get; set; }
public string ScopeDisplay1 { get; set; }
public
List<TScopeType> ScopeTypes1 { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UsingAutoMapper.Models
{
public class ScopeViewModel
{
public int ScopeId { get; set; }
public string ScopeName { get; set; }
/// <summary>
/// Id + Name
/// </summary>
public string ScopeDisplay { get; set; }
public
List<TScopeTypeViewModel> ScopeTypes { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UsingAutoMapper.Models
{
public class TScopeType
{
public int ScopeTypeId { get; set; }
public string ScopeTypeName { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UsingAutoMapper.Models
{
public class TScopeTypeViewModel
{
public int ScopeTypeId { get; set; }
public string ScopeTypeName { get; set; }
}
}
0 comments:
Post a Comment