简体   繁体   中英

Automapper custom map configuration problem

I have two classes with " Points " member in both, but in one of them Points are string type and string[][] in anather class.

I use Automapper and the next configuration

x.CreateMap<ProblemViewModel, Problem>()
                    .ForMember(dest => dest.Points,
                        src => src.MapFrom{PointsForDbResolver}())
                    .ReverseMap()
                .ForMember(dest => dest.Points,
                    src => src.MapFrom{PointsForViewResolver}());

with custom value resolvers "PointsForDbResolver" and "PointsForViewResolver" (both are IValueResolver) that convert mentioned types in each other. But I get error:

Exception Details: System.InvalidOperationException: Sequence contains no elements

Coud you help me to resolve this problem and is it possible this transformation to be done by Automapper.

Next is resolver from string[][] to string

public class PointsToDbResolver : IValueResolver<ProblemViewModel, Problem, string>
{
    public string Resolve(
        ProblemViewModel source,
        Problem destination,
        string destMember, 
        ResolutionContext context)
    {
        if (source == null)
        {
            return null;
        }

        StringBuilder result = new StringBuilder();
        for (int row = 0; row < source.Points.GetLength(0); row++)
        {
            for (int col = 0; col < source.Points[row].Length; col++)
            {
                result.Append(source.Points[row][col]).Append(Constants.PointsColSeparator);
            }
            result.Replace(
                Constants.PointsColSeparator,
                Constants.PointsRowSeparator,
                result.Length - 1, 1);
        }
        result.Remove(result.Length - 1, 1);

        return result.ToString();
    }

and from string to string[][]

public class PointsToViewResolver : IValueResolver<Problem, ProblemViewModel, string[][]>
{
    public string[][] Resolve(
        Problem source,
        ProblemViewModel destination,
        string[][] destMember, 
        ResolutionContext context)
    {
        if (source.Points == null)
        {
            return new string[0][];
        }

        var rows = source.Points.Split(new string[] { Constants.PointsRowSeparator },
            StringSplitOptions.None);
        string[][] result = new string[rows.Length][];
        for (int row = 0; row < rows.Length; row++)
        {
            result[row] =
                rows[row].Split(new string[] { Constants.PointsColSeparator },
                StringSplitOptions.None);
        }

        return result;
    }
}

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