-
安装依赖包
- 创建model
namespace DTOMapper.Model
{
public class Person
{
public int? ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool? Sex { get; set; } = true;
public DateTime BirthDay { get; set; }
public string? Address { get; set; }
}
}
- 创建config
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DTOMapper.Model
{
public class PersonConfig : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.ToTable("person");
builder.HasKey(x => x.ID);
builder.Property(x => x.ID).HasColumnName("id").ValueGeneratedOnAdd();
builder.Property(x => x.BirthDay).HasColumnName("birthday");
builder.Property(x => x.FirstName).HasColumnName("firstname");
builder.Property(x => x.LastName).HasColumnName("lastname");
builder.Property(x => x.Sex).HasColumnName("sex");
builder.Property(x => x.Address).HasColumnName("address");
}
}
}
- 创建dbhelper
using Microsoft.EntityFrameworkCore;
namespace DTOMapper.Model
{
public class DBHelper:DbContext
{
public DbSet<Person> Persons { get; set; }
public DBHelper(DbContextOptions<DBHelper> opetions):base(opetions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
}
}
- 创建DTO以及automapper
using AutoMapper;
namespace DTOMapper.Model
{
public class PersonDTO
{
public int ID { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
#这是class转成DTO,形如GET接口
public class PersonToDTOMapper : Profile
{
public PersonToDTOMapper()
{
CreateMap<Person, PersonDTO>()
.ForMember(dest => dest.Age, opt => opt.MapFrom(src => DateTime.Now.Year - src.BirthDay.Year))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => $"{ src.FirstName}{src.LastName}"))
.ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.ID));
}
}
#这个是在dto转成class时候使用,形如post接口
public class PersonDTOTOPerson : Profile
{
public PersonDTOTOPerson()
{
CreateMap<PersonDTO, Person>().AfterMap((dto, person) => person.FirstName = dto.Name.Split(':')[0])
.AfterMap((dto, person) => person.LastName = dto.Name.Split(':')[1])
//.ForMember(x => x.LastName, opt => opt.MapFrom(src => GetName(src.Name, 1))); 这种以及上述的aftermap均可
.ForMember(x => x.BirthDay, opt => opt.MapFrom(src => GetBirthday(src.Age)))
.ForMember(x=>x.ID,opt=>opt.Ignore());//这个是忽略传入的ID,数据库自动生成即可
}
public string GetName(string value, int index)
{
return value.Split(':')[index];
}
public DateTime GetBirthday(int age)
{
DateTime dt = DateTime.UtcNow;
return dt.AddYears(-age);
}
}
}
- controller
using DTOMapper.Model;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace DTOMapper.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class EllisController : ControllerBase
{
public readonly DBHelper _dBHelper;
private readonly IMapper _mapper;
public EllisController(DBHelper dBHelper, IMapper mapper)
{
_dBHelper = dBHelper;
_mapper = mapper;
}
// GET: api/<EllisController>
[HttpGet]
public PersonDTO Get(int id)
{
var value = _dBHelper.Persons.Where(x=>x.ID == id).FirstOrDefault();
PersonDTO result = _mapper.Map<PersonDTO>(value);
return result;
}
[HttpPost]
public bool Post([FromBody]PersonDTO value)
{
var person = _mapper.Map<Person>(value);
_dBHelper.Persons.Add(person);
_dBHelper.SaveChanges();
return true;
}
}
}
- programe.cs
builder.Services.AddDbContext<DBHelper>(opt =>
{
opt.UseNpgsql(@"Host=192.168.214.133;Port=32222;Database=postgresdb;Username=postgresadmin;Password=admin123");
});
//一次添加多个mapper
builder.Services.AddAutoMapper(typeof(PersonToDTOMapper),typeof(PersonDTOTOPerson));
建表语句
CREATE TABLE public.person (
id bigserial NOT NULL,
firstname varchar NULL,
lastname varchar NULL,
birthday timestamptz NULL,
address varchar NULL,
sex bool null,
primary key(id)
);
https://stackoverflow.com/questions/4987872/ignore-mapping-one-property-with-automapper
https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e
https://stackoverflow.com/questions/54858116/using-string-split-in-automapper-issue
版权声明:本文为weixin_43632687原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。