代码之家  ›  专栏  ›  技术社区  ›  jmathew

爆米花API:如何在自定义翻译上实现扩展?

  •  2
  • jmathew  · 技术社区  · 7 年前

    我正在使用 Popcorn 允许API的客户端指定分解请求对象属性的深度。

    数据模型如下所示:

    public class DataModel {
        public List<Person> Persons { get; set; }
    }
    
    public class Person {
        public Guid Id { get; set; }
        public List<Pet> Pets {get; set;}
    
        public List<Pet> GetLivingPets() {
           // Do some computation to get the pets that are alive
        }
    }
    
    public class Pet {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public bool Alive { get; set; }
    }
    
    public PetProjection {
        public Guid? Id { get; set; }
        public string Name { get; set; } 
    }
    
    
    public PersonProjection {
        public Guid? Id { get; set; }
        public List<PetProjection> LivingPets {get; set;}
    }
    

    我希望我的客户能够发出请求,指定动态生成的列表的嵌套。 http://localhost:5000/api/1/Persons?include=[Id,LivingPets[Name]]

    返回如下列表:

    [
        {
            "Id": "00000000-0000-0000-0000-000000000000",
            "LivingPets": [
                {
                    "Name": "Capt Meowmix"
                }
            ]
        }
    ]
    

    这是我正在尝试的映射:

    popcornConfig
    .Map<Person, PersonProjection>(config: (personConfig) =>
    {
    
         personConfig.Translate(fp => fp.LivingPets, f => f.GetLivingPets()?.ToList()); // Error: 'Dictionary<string, object>' does not contain a definition for 'GetLivingPets' and no extension method 'GetLivingPets' accepting a first argument of type 'Dictionary<string, object>' could be found (are you missing a using directive or an assembly reference?)   
    
    })
    .MapEntityFramework<Pet, PetProjection, DataModel>(dbContextOptionsBuilder);
    

    我需要做什么来编写一个映射,以利用我已经定义的另一个映射?这是图书馆可以做的事吗?我错过什么了吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Nicholas M T Elliott    7 年前

    没有必要 Translate 在…上 LivingPets . 爆米花会自动在映射实体及其投影之间查找相同的命名属性。它将查找匹配的属性,或者不匹配不需要参数的方法,因此如果您命名您的方法 它会自动工作。然而,你在做什么翻译应该 工作

    关于translate函数,只要它返回一个对象Popcorn有一个映射,客户端就应该能够扩展它。您看到该错误是因为编译器选择了错误版本的Translate函数。如果你换了

    personConfig.Translate(fp => fp.LivingPets, f => f.GetLivingPets()?.ToList());
    

    personConfig.Translate(fp => fp.LivingPets, (f,c) => f.GetLivingPets()));
    

    编译错误应该消失。这是一个bug,正在中跟踪 this issue .