Automapper: map a property of a collection to an array throws NotSupportedException

Created on 3 Jan 2017  路  7Comments  路  Source: AutoMapper/AutoMapper

I'm using Automapper 5.2.0 with EF 6.1.3 in web api project.

public class PushNotification
{
    public int[] Stores { get; set; }
}

public class PushNotificationEntity
{
    [Key]
    public int Id { get; set; }
    public ICollection<StoreEntity> Stores { get; set; }
}

public class StoreEntity
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<PushNotificationEntity> PushNotifications { get; set; }
}

mapping,

cfg.CreateMap<PushNotificationEntity, PushNotification>()
                .ForMember(dest => dest.Stores,
                            opts => opts.MapFrom(src => src.Stores.Select(s => s.Id).ToArray()));

using the mapper,

var item = ctx.PushNotifications.Include(p => p.Stores)
            .Where(n => n.Id == id).ProjectTo<PushNotification>(mapperCfg).SingleOrDefault();

I'm getting following error,

System.NotSupportedException.
LINQ to Entities does not recognize the method 'Int32[]
ToArray[Int32](System.Collections.Generic.IEnumerable`1[System.Int32])'
method, and this method cannot be translated into a store expression.

Most helpful comment

This is not an issue with AutoMapper but with EF. Your error message it says ToArray won't work with EF. EF doesn't know how to translate ToArray into a T-SQL statement. I know it's weird cause LinqToSQL can do this no problem.

ToList can be translated fine though.

All 7 comments

Does ToArray work without AutoMapper? Try writing a Select LINQ expression to manually map with EF. I'd try ToList first.

ToArray() outside of AutoMapper works fine. ToList() also works. Wierd.

This is not an issue with AutoMapper but with EF. Your error message it says ToArray won't work with EF. EF doesn't know how to translate ToArray into a T-SQL statement. I know it's weird cause LinqToSQL can do this no problem.

ToList can be translated fine though.

@TylerCarlson1, You mean mapping happens in DB? The mapping logic is translated to T-SQL? I thought the mapping is done in .Net side after fetching the entity from the DB.

No, ProjectTo builds a LINQ expression to pass to the query provider. That mapping expression is then translated to SQL. The advantage is that it bypasses your entities and the SQL is only the data projecting to your DTO. The disadvantage is you're limited by what the query provider can understand. EF is generally the most feature-rich in this area, but if you hit issues like this, you need to verify you can build the LINQ expression without AutoMapper.

This can be closed.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings