AutoMapper映射问题:如何将SourceEntity列表映射到DestEntity集合
AutoMapper Mapping Solution for Your Entity Structure
Hey there! Since you're new to AutoMapper, let's break down exactly how to set up the mapping to match the manual logic you've already written.
Step 1: Create a Custom Mapping Profile
First, you'll need to define a mapping profile that encapsulates the logic to convert SourceEntity to DestEntity. This is where we'll replicate your manual list-checking and object creation flow:
public class EntityMappingProfile : Profile { public EntityMappingProfile() { CreateMap<SourceEntity, DestEntity>() .ForMember(dest => dest.DestinationObjects, opt => opt.MapFrom(src => { var destinationItems = new List<SubDestinationEntity>(); // Check if List1 has elements and add the corresponding SubDestinationEntity if (src.List1?.Any() == true) { destinationItems.Add(new SubDestinationEntity { Title = "Some text 1", Objects = src.List1 }); } // Repeat the check for List2 if (src.List2?.Any() == true) { destinationItems.Add(new SubDestinationEntity { Title = "Some text 2", Objects = src.List2 }); } return destinationItems; })); } }
Step 2: Initialize AutoMapper with the Profile
Next, set up your AutoMapper configuration to use this profile, then create a mapper instance for actual conversions:
// Configure AutoMapper with our custom profile var mapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile<EntityMappingProfile>(); }); // Optional but recommended: Validate the configuration to catch issues early mapperConfig.AssertConfigurationIsValid(); // Create the mapper instance var mapper = mapperConfig.CreateMapper();
Step 3: Use the Mapper in Your Code
Now you can map your source entity to the destination entity just like you would with standard AutoMapper setups:
// Example source entity with sample data var source = new SourceEntity { List1 = new List<object> { "Item 1", "Item 2" }, List2 = new List<object> { "Item 3" } }; // Perform the mapping var destination = mapper.Map<DestEntity>(source); // Result: destination.DestinationObjects will have two SubDestinationEntity instances // One with Title "Some text 1" (linked to List1) and another with "Some text 2" (linked to List2)
Quick Tips
- The
?.Any() == truecheck safely handles null source lists, so you won't run intoNullReferenceExceptionifList1orList2is uninitialized. - Using
MapFromlets us inject custom logic directly into the mapping process, which is ideal when standard property-to-property mapping doesn't fit your needs.
内容的提问来源于stack exchange,提问作者Gleb
相关产品推荐
相关产品推荐

