首次在仓储类库中使用AutoMapper,基于现有配置代码求技术帮助
Hey there! As someone who's worked with AutoMapper for years, let's walk through your setup, highlight what's working, fix common first-time pitfalls, and tweak things for robustness.
First: Validate Your Core Setup
Your structure—using a static config class and a dedicated Profile to organize mappings—is totally on the right track. That's AutoMapper's recommended approach for keeping mapping rules clean. But there's one key thing to note if you're using AutoMapper 9.0 or newer:
The static Mapper.Initialize method is obsolete. Instead, you should create a MapperConfiguration instance (which is immutable and thread-safe) and inject IMapper into your services. Here's how to update your config class:
public static class AutoMapperWebConfig { public static MapperConfiguration Configure() { return new MapperConfiguration(config => { config.AddProfile(new WebConfigurationProfile()); }); } }
Then, in your app's startup code (like Startup.cs for ASP.NET):
// Build the config and validate it immediately var mapperConfig = AutoMapperWebConfig.Configure(); mapperConfig.AssertConfigurationIsValid(); // Catches mapping errors early // Inject IMapper for dependency injection services.AddSingleton(mapperConfig.CreateMapper());
This avoids the pitfalls of static state and aligns with modern .NET dependency injection best practices.
Common Issues You're Likely Facing (And Fixes)
Let's cover the most frequent problems first-time AutoMapper users run into:
Mapping runs but properties are null
- Double-check access modifiers: Ensure
PovUsers.PovUserName,PovUsers.PovUserId, andPovUserView.Name/PovUserView.Userare allpublic. AutoMapper can't map non-public members by default. - Confirm your config is initialized: Make sure you're calling
AutoMapperWebConfig.Configure()(and creating the mapper instance) when your app starts. If you skip this, AutoMapper won't know about your mapping rules.
- Double-check access modifiers: Ensure
"No mapping found for types" exceptions
- Verify you're using the correct order of types when mapping: It's
Map<DestinationType>(SourceObject), not the other way around. Example:// Correct var userView = _mapper.Map<PovUserView>(myPovUser); // Wrong (will throw an error) var userView = _mapper.Map<PovUsers>(myPovUserView); - Use
AssertConfigurationIsValid()(as shown earlier) during startup—it'll throw a detailed exception if any mapping rules are broken (like a target property with no source mapping).
- Verify you're using the correct order of types when mapping: It's
Unwanted null values on other properties
- If
PovUsersandPovUserViewhave additional properties you don't want to map, explicitly ignore them to avoid unexpected nulls:CreateMap<PovUsers, PovUserView>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.PovUserName)) .ForMember(dest => dest.User, opt => opt.MapFrom(src => src.PovUserId)) .ForAllOtherMembers(opt => opt.Ignore()); // Ignore unconfigured properties
- If
Quick Tweaks to Clean Up Your Profile
A small improvement to make your profile more readable:
- You don't need
this.when callingCreateMapinside the Profile constructor—just call it directly. Also, usingdest/srcinstead ofx/pmakes the intent clearer:
public class WebConfigurationProfile : Profile { public WebConfigurationProfile() { CreateMap<PovUsers, PovUserView>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.PovUserName)) .ForMember(dest => dest.User, opt => opt.MapFrom(src => src.PovUserId)); } }
If you ever need to debug mapping issues, adding a name to your Profile can help:
public WebConfigurationProfile() : base("WebApplicationProfile") { ... }
That's it! If you hit a specific error (like a stack trace or unexpected behavior), feel free to share more details and we can dig deeper.
内容的提问来源于stack exchange,提问作者Martin BudSide

