formatc
formatc

Reputation: 4323

Automapper mapping EF projectable properties first, then other properties

I have something like this:

        Mapper.CreateMap<UserProfile, UserDTO>()
            .ForMember(t => t.UserImage, s => s.MapFrom(x => x.Picture(32)))
            .ForMember(t => t.Permalink, s => s.MapFrom(x => x.Permalink()));

And I try something like this:

   unit.UserProfiles.GetAll().Project().To<UserDTO>().First();

I get something like:

LINQ to Entities does not recognize the method 'System.String Picture(xx.xxx.UserProfile, Int32)' method, and this method cannot be translated into a store expression.

I would like to tell automapper to project map every property other then those two and after query is done to map those two in normal way, is it doable?

Upvotes: 2

Views: 901

Answers (1)

Jimmy Bogard
Jimmy Bogard

Reputation: 26765

You're asking the wrong question here. You really need to ask "how can my underlying query provider defer some of the projection to after the queryable does its job". This would involve a two-step process that Entity Framework would need to support. Here's the code, without AutoMapper going on:

unit.UserProfiles.Select(profile => new UserDTO {
    Id = profile.Id, // I made these two up
    Name = profile.Name,
    UserImage = profile.Picture(32),
    Permalink = profile.Permalink()
}).First();

How would EF interpret this? Not well, I assume. Probably an exception. If you wanted to do this in EF, you'd need to do something like:

unit.UserProfiles.Select(profile => new UserDTO {
    Id = profile.Id, // I made these two up
    Name = profile.Name
    UserImage = profile.UserImage,
    Slug = profile.Slug
}).First();

And then include the logic of creating a picture as part of UserDTO.

Alternatively, you'd just get the User out, and map afterwards. The key here is that AutoMapper only creates a Select projection, and it's up to the underlying query provider to handle it appropriately. AutoMapper can't guess what is supported or not, nor can it know how to resolve your custom methods, which are on the source type, and what data is needed from SQL.

Ask first - how would I accomplish this with a Select projection in EF? Then AutoMapper will take care of encapsulating that projection.

Upvotes: 2

Related Questions