How to map the first item in a collection using AutoMapper

I have a Foo gen'd object with EF, it has the navigation property Bar, which is one for many, but should have been one to one. Anyway, when I request Foo, I also like getting the first and only item from the Bar collection and matching them with aligned Biz Dto, how would I do it?

        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 would 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???))

Thanks Steven

+5
source share
2 answers

Use FirstOrDefault()in collection Barwhen displaying it:

opt.MapFrom(src => src.Bar.FirstOrDefault())
+6
source

Given:

public class Foo{
 public ICollection<Bar> Bars { get; set; }
}

Decision:

var result = from item in FooCollection
             select new { FirstBar = item.Bars.FirstOrDefault() };

Where FooCollection is IQueryable<Foo>

FirstOrDefault, ,

, ...

0

All Articles