You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何用AutoMapper简化DTO到模型的属性赋值操作?

Simplifying DTO-to-Model Mapping with AutoMapper

Absolutely! That’s exactly the kind of repetitive, boilerplate code AutoMapper was built to eliminate. No more manually assigning every property one by one—let me walk you through how to streamline this workflow.

Step 1: Define Your Mapping Profile

First, create an AutoMapper Profile class to formalize how your DTO maps to your model. This is where you handle any property name mismatches or custom logic; most of the time, if property names match, AutoMapper will handle them automatically.

using AutoMapper;

public class YourEntityMappingProfile : Profile
{
    public YourEntityMappingProfile()
    {
        // Base mapping for all matching property names (Property1, Property2, etc.)
        CreateMap<YourDto, YourModel>()
            // Fix the mismatched property you mentioned in your example
            .ForMember(dest => dest.SomePropertyType, 
                opt => opt.MapFrom(src => src.PropertyType));
        
        // No need to define rules for Property1/Property2—AutoMapper handles those automatically!
    }
}

Step 2: Register AutoMapper with Dependency Injection

Next, register AutoMapper in your application's service container (typically in Program.cs for .NET 6+):

builder.Services.AddAutoMapper(typeof(YourEntityMappingProfile));

Step 3: Replace Manual Assignments with AutoMapper

Instead of writing lines and lines of property assignments, inject IMapper into your service or mapping class and use the Map method to handle all the heavy lifting.

Option 1: Create a new model from the DTO

public class YourMappingService
{
    private readonly IMapper _mapper;

    public YourMappingService(IMapper mapper)
    {
        _mapper = mapper;
    }

    public YourModel ConvertDtoToModel(YourDto dto)
    {
        // One line replaces all your manual property assignments!
        return _mapper.Map<YourModel>(dto);
    }
}

Option 2: Update an existing model instance

If you need to overwrite properties on an already existing model (common for edit operations), use the overload that accepts both the source DTO and target model:

public void UpdateModelFromDto(YourDto dto, YourModel existingModel)
{
    _mapper.Map(dto, existingModel);
    // All matching properties (and your custom mapped property) are updated automatically
}

Bonus: Handling Edge Cases

  • Nested objects: AutoMapper will automatically map nested DTOs to nested models if you define corresponding mapping profiles for them.
  • Custom logic: For things like enum conversions, date formatting, or calculated values, use ConvertUsing or MapFrom with a lambda or custom method in your profile.

This approach not only cleans up your code immediately but also scales better—if you add new properties to your DTO/model later, AutoMapper will map them automatically as long as the names match, no extra code required.

内容的提问来源于stack exchange,提问作者Joseph Meris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:37:15