1.Add Mapster packages from NuGet
<package id="Mapster" version="7.3.0" targetFramework="net48" />
<package id="Mapster.Core" version="1.2.0" targetFramework="net48" />
2.Create Source class
//Source or DTO
public class TempCacheDto
{
public int Id { get; set; }
public string SerialNumber { get; set; }
}
3.Create Destination class
//Destination or Entity Db object
public class TempCache
{
public int Id { get; set; }
public string SerialNumber { get; set; }
}
4.Create Service or repository class where mapping required to convert Dto to Enity object.
Simple Save and Retrieve example below for using mapster and entity framework.
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TempCache.Repositories
{
public class TempCacheRepository
{
//save data from dto model to entity using mapster
public bool Save(TempCacheModel bcTempCache)
{
using (var context = new DbContext())
{
if (bcTempCache.Id == 0)
{
TempCache entity = bcTempCache.Adapt<TempCache>();
context.TempCaches.Add(entity);
}
else
{
TempCache exist = context.TempCaches
.FirstOrDefault(x => x.Id == bcTempCache.Id);
if (exist != null)
{
exist = bcTempCache.Adapt<TempCacheModel, TempCache>(exist);
}
else
{
return false;
}
}
context.SaveChanges();
return true;
}
}
//get list from Db and retun as dto list using mapster
public List<TempCacheModel> TempCaches()
{
using (var context = new DbContext())
{
return context.TempCaches.ToList().Adapt<List<TempCacheModel>>();
}
}
//get list from Db and retun as dto list using mapster
public TempCacheModel GetById(int id)
{
using (var context = new DbContext())
{
return context.TempCaches.FirstOrDefault(x=>x.Id==slNo)?
.Adapt<TempCacheModel>();
}
}
}
}
Why Mapster over Auto mapper
Method | Mean | StdDev | Error | Gen 0 | Gen 1 | Gen 2 | Allocated |
---|---|---|---|---|---|---|---|
'Mapster 6.0.0' | 108.59 ms | 1.198 ms | 1.811 ms | 31000.0000 | - | - | 124.36 MB |
'Mapster 6.0.0 (Roslyn)' | 38.45 ms | 0.494 ms | 0.830 ms | 31142.8571 | - | - | 124.36 MB |
'Mapster 6.0.0 (FEC)' | 37.03 ms | 0.281 ms | 0.472 ms | 29642.8571 | - | - | 118.26 MB |
'Mapster 6.0.0 (Codegen)' | 34.16 ms | 0.209 ms | 0.316 ms | 31133.3333 | - | - | 124.36 MB |
'ExpressMapper 1.9.1' | 205.78 ms | 5.357 ms | 8.098 ms | 59000.0000 | - | - | 236.51 MB |
'AutoMapper 10.0.0' | 420.97 ms | 23.266 ms | 35.174 ms | 87000.0000 | - | - | 350.95 MB |
No comments:
Post a Comment