简体   繁体   中英

Automapper: How to Map an Object if Not Null Using EF

I am new to automapper. I am trying to map an object to a DTO. The object has a locationId which is nullable. I need to either assign empty string to the DTO's "LocationName" property if locationId is null OR select the locationName from a table in SQL using EF. How do I accomplish this?

The classes:

public class Foo
{
        public int id { get; set; } //not relevant, here for convention
        public int? LocationId { get; set; } 
}

public class FooDto
{
        public int id { get; set; } //not relevant, here for convention
        public string LocationName { get; set; }
}

My attempt:

Mapper.CreateMap<Foo, FooDto>()
    .ForMember( dest => dest.locationName, options => options.ResolveUsing(src=> src.LocationId == null ? "" : src => db.Locations.SingleOrDefault(l => l.Id == src.LocationId).Name) )

I used this as an example, but it's not using EF, so I have no idea what I am doing wrong. I never did get a clear answer on MapFrom vs ResolveUsing either from various sources such as this .

My concern was the fact that I am mapping one property type to another and using EF. The fact is that automapper does not care. This code works:

Mapper.CreateMap<Foo, FooDto>()
    .ForMember( dest => dest.locationName, opt => opt.ResolveUsing(src=> src.LocationId == null ? "" : db.Locations.SingleOrDefault(l => l.Id == src.LocationId).Name) )

I was overthinking it, when the issue was in my lambda expression. I passed the argument twice because I wasn't thinking about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM