C# 自动映射:将其设置为属性
使用AutoMapper是否可以做到这一点:将源对象放在目标对象的私有属性中 以下是我想做的事情:C# 自动映射:将其设置为属性,c#,automapper,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
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);
}
}
}
使用系统;
使用系统诊断;
使用自动制版机;
名称空间控制台AP12{
B类{
公共B(){}
}
甲级{
公共B{get;私有集;}
公共A(){}
}
班级计划{
静态void Main(字符串[]参数){
var config=new-MapperConfiguration(cfg=>
cfg.CreateMap()
.ForMember(ma=>ma.B,mb=>mb)//错误mb不能是“this”
);
变量映射器=新映射器(配置);
var b=新的b();
var a=映射器.Map(b);
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);
}
}
``
void Main()
{
}
B类
{
公共int MyProperty{get;set;}
公共B(){}
}
甲级
{
公共B{get;私有集;}
公共A(){}
}
班级计划
{
静态void Main(字符串[]参数)
{
var config=new-MapperConfiguration(cfg=>
{
cfg.CreateMap()
.ForMember(dest=>dest.B,opt=>opt.MapFrom(src=>src));
});
变量映射器=新映射器(配置);
var b=new b(){MyProperty=123};
var a=映射器.Map(b);
config.assertconfigurationsvalid();
Assert(a.B!=null);
Assert(a.B.MyProperty==123);
}
}
``
您有能力将B添加为构造函数的参数吗?这是可能的,但在这种情况下,构造函数必须是私有的或受保护的。在这么简单的时候,我觉得太复杂了。非常感谢。@Topic很高兴能提供帮助,我也一直在探索AutoMapper的简单功能的启蒙之旅中!:-)我还在学习!