【问题标题】:AutoMapper: Pass a parameter to destination contructor when using .ProjectToAutoMapper:使用 .ProjectTo 时将参数传递给目标构造函数
【发布时间】:2018-12-24 02:03:05
【问题描述】:

我的目标对象有一个参数构造函数,我需要将一个对象传递给它以供内部使用。 我如何将其传递给 ProjectTo

-映射

CreateMap<SomeEntity, SomeModel>();

-投影

var param = new SomeContructorParam();
await context.SomeEntities                    
                .ProjectTo<SomeModel>() --  PASS PARAM here? how so
                .ToListAsync();

-目标对象

public class SomeModel
{
    private readonly SomeContructorParam ctorParam;
    public SomeModel(SomeContructorParam ctorParam)
    {
        this.ctorParam = ctorParam;
    }
    ...

}
public class SomeContructorParam
{
    ...
}

【问题讨论】:

  • 这个对于DI还是只需要传入一个参数。
  • 我已经看过了,但无法弄清楚如何将它传递给构造函数,这些示例假设我正在分配目的地的公共属性,在我的情况下,请参阅更新 dest 模型代码的 OP
  • @TheGeneral 最后一个链接假定我的构造函数参数来自源对象,还是我读错了那个文档?传递给 dest 的参数不是来自源代码,而是来自外部,如您在给出的示例中所见(修改了原始代码)

标签: c# automapper


【解决方案1】:

久经考验。

映射:

SomeContructorParam emptyParm = null
CreateMap<SomeEntity, SomeModel>()
    .ConstructUsing(src => new SomeModel(emptyParm));

投影

var param = new SomeContructorParam();
await context.SomeEntities                    
            .ProjectTo<SomeModel>(new { emptyParm = param })
            .ToListAsync();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多