Randy Minder
Randy Minder

Reputation: 48542

Need help with AutoMapper

I have two classes that looks as follows:

public class Rule
{
    public int Id { get; set; }
    public RuleGroup RuleGroup { get; set; }
}


public class RuleGroup
{
    public int Id { get; set; }
    public List<Rule> RuleList { get; set; }
}

A RuleGroup has a list of rules. My AutoMapper settings are as follows:

Mapper.CreateMap<RuleRecord, FirstSolar.Mes.Core.Entities.Recipe.Rule>()
   .ForMember(destination => destination.RuleGroup, source => source.Ignore())
   .ForMember(destination => destination.Id, source => source.MapFrom(item => item.RuleId));
Mapper.CreateMap<IList<RuleRecord>, IList<FirstSolar.Mes.Core.Entities.Recipe.Rule>>();

Mapper.CreateMap<RuleGroupRecord, FirstSolar.Mes.Core.Entities.Recipe.RuleGroup>()
   .ForMember(destination => destination.Id, source => source.MapFrom(item => item.RuleGroupId));
Mapper.CreateMap<IList<RuleGroupRecord>, IList<FirstSolar.Mes.Core.Entities.Recipe.RuleGroup>>();

When I attempt to map a RuleGroupRecord (LinqToSQL object) to RuleGroup (DTO), AutoMapper says I need to add a mapping for RuleGroup.RuleList. I'm wondering why because I defined how to map a single RuleRecord and a List.

If I have to, how would I do it?

Upvotes: 0

Views: 251

Answers (1)

Femaref
Femaref

Reputation: 61497

Simply add (I hope I got the syntax right, but you should see what I'm hinting at):

.ForMember(destination => destination.RuleList, source => source.MapFrom(item => item.Rules));

to the second mapping. While you handled the general mapping for RuleRecord to Rule in the first mapping, you didn't tell automapper to map the specific property RuleGroup.RuleList.

Upvotes: 2

Related Questions