这里写目录标题
- C#
- 创建AutoMapper的映射配置代码实现
- 定义实体类(Entities)
- 定义模型类(Model)
- 配置及调用
- C# ASP.NET Core微服务
- 创建AutoMapper的映射配置代码实现
- 定义实体类(Entities)
- 定义模型类(Model)
- 创建 AutoMapper 的映射配置
- 添加到微服务
- 调用
C#
创建AutoMapper的映射配置代码实现
定义实体类(Entities)
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public string FieldName { get; set; }
}
定义模型类(Model)
public class Model
{
public int Identifier { get; set; }
public string Title { get; set; }
public string FieldName { get; set; }
}
配置及调用
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Entity, Model>()
.ForMember(dest => dest.Identifier, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Name))
.ForMember(_ => _.FieldName, opt => opt.Ignore());
});
var mapper = config.CreateMapper();
var entity = new Entity
{
Id = 1,
Name = "Example"
};
var model = mapper.Map<Model>(entity);
C# ASP.NET Core微服务
创建AutoMapper的映射配置代码实现
定义实体类(Entities)
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public string FieldName { get; set; }
}
定义模型类(Model)
public class Model
{
public int Identifier { get; set; }
public string Title { get; set; }
public string FieldName { get; set; }
}
创建 AutoMapper 的映射配置
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Entity, Model>()
.ForMember(dest => dest.Identifier, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Name))
.ForMember(_ => _.FieldName, opt => opt.Ignore());
}
}
添加到微服务
services.AddAutoMapper(typeof(MappingProfile))
调用
mapper.Map<Model>(entity);