Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

.net - AutoMapper fails to map protobuf's RepeatedField in projection

I am currently converting a Web Api from REST to gRPC. This Api uses AutoMapper to convert from database entities into Dto's on the fly.

The problem I am facing now is that any RepeatedField members remain empty after the mapping. I have tried various supposed solutions from SO and GitHub, like custom type converters and UseDestinationValue() but nothing seems to work.

I have created a sample test project which demonstrates the problem. The project contains only 2 tests, one using the Mapper with and one without projection. The projection test in this sample will fail.

Person entity:

public class Person
{
    public int Id { get; set; }
    public ICollection<Pet> Pets { get; set; }
}

Pet entity:

public class Pet
{
    public int Id { get; set; }
    public int PersonId { get; set; }
    public string Name { get; set; }
}

PersonDto (protobuf):

syntax = "proto3";
option csharp_namespace = "AutoMapperRepeatedFieldTests.Protos";

message PersonDto {
    string Name = 1;
    repeated string PetNames = 2;
}

AutoMapper config:

public MyMappingConfig()
{
    CreateMap<Person, PersonDto>()
        .ForMember(x => x.PetNames, m => m.MapFrom(x => x.Pets.Select(pet => pet.Name)))
        .ReverseMap();

    // Supposed solution from https://github.com/AutoMapper/AutoMapper/issues/3325#issuecomment-593076419
    ForAllPropertyMaps(
        map => map.DestinationType.IsGenericType && map.DestinationType.GetGenericTypeDefinition() == typeof(RepeatedField<>),
        (map, options) => options.UseDestinationValue());
}

Test (Assert.AreEqual will fail):

var mapper = GetMapper();
var query = db.Set<Person>();
var projectionResult = query.ProjectTo<PersonDto>(mapper.ConfigurationProvider);

Assert.AreEqual(1, projectionResult.Count());

Any ideas how I could resolve this?

Test repo: https://github.com/Akinzekeel/AutoMapperRepeatedFieldTests

Test fails on this line specifically: https://github.com/Akinzekeel/AutoMapperRepeatedFieldTests/blob/master/AutoMapperRepeatedFieldTests/Tests.cs#L73

question from:https://stackoverflow.com/questions/65875287/automapper-fails-to-map-protobufs-repeatedfield-in-projection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...