Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map the first item in a collection with AutoMapper

I have an object Foo gen'd with EF, it has a navigation property of Bar that is one to many, but should have been one to one. Anyways, when I query for a Foo I's also like to get the First and only item from the Bar collection and map these to a flattened out Biz Dto, how would I go about doing that?

        var result = (from c in ctx.Foo
                     where c.Bar.Any(cs => cs.LOGINNAME == username && cs.PASSWORD == password)
        select c).First();

Then in my AutoMapper Configuration I'd create a map that looked like????

        Mapper.CreateMap<Foo, Biz>()
            .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.CLIENTID))
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Bar.FirstOrDefault???))

Thank you, Stephen

like image 846
Stephen Patten Avatar asked Nov 21 '11 23:11

Stephen Patten


Video Answer


1 Answers

Use FirstOrDefault() on the Bar collection when you map it:

opt.MapFrom(src => src.Bar.FirstOrDefault())
like image 100
PatrickSteele Avatar answered Nov 15 '22 09:11

PatrickSteele