c# - Automapper:将此设置为属性
问题描述
是否可以使用 AutoMapper 做到这一点:将源对象放在目标对象的私有属性中。
在我想做的情况下:
using System;
using System.Diagnostics;
using AutoMapper;
namespace ConsoleApp12 {
class B {
public B() { }
}
class A {
public B B { get; private set; }
public A() { }
}
class Program {
static void Main(string[] args) {
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<B, A>()
.ForMember(ma => ma.B, mb => mb) //Error mb can't be "this"
);
var mapper = new Mapper(config);
var b = new B();
var a = mapper.Map<A>(b);
Debug.Assert(a.B != null);
}
}
}
解决方案
我认为您在成员映射中需要稍微不同的语法。
请注意,第二个参数不是您要映射的值,而是通过 MapFrom 表达的如何获取该值的表达式。
我更改了 lambda 表达式参数以使其更易于阅读,并添加了一个虚拟属性来证明这一点。
void Main()
{
}
class B
{
public int MyProperty { get; set; }
public B() { }
}
class A
{
public B B { get; private set; }
public A() { }
}
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<B, A>()
.ForMember(dest => dest.B, opt => opt.MapFrom(src => src));
});
var mapper = new Mapper(config);
var b = new B() { MyProperty = 123 };
var a = mapper.Map<A>(b);
config.AssertConfigurationIsValid();
Debug.Assert(a.B != null);
Debug.Assert(a.B.MyProperty == 123);
}
}
``
推荐阅读
- java - java中的服务器和客户端程序:客户端需要开始和结束对话
- javascript - 可重用的反应组件时间线
- python - 如何仅使用 scikit-learn 消除停用词?
- html - 内部样式在此 HTML 代码中不起作用?
- javascript - 比较 getDerivedStateFromProps 中的不同状态数组
- arduino - 程序没有进入子程序?
- r - 我分离了包裹,现在我无法赋值
- docker - API Gateway w/WebAPI 端点在同一用户桥接网络上。WebAPI 需要 SSL?
- php - 如何进行登录尝试失败的系统
- wxwidgets - 我想从内存中的 xml 字符串加载 wxwidgets。