Automapper - 为什么不使用 SourceMember 属性进行映射
Automapper - Why isn't it mapping using SourceMember Attributes
为什么 Automapper 不使用 SourceMember 属性映射到 Employee?如果我将名称与名称相匹配:
无效:
https://dotnetfiddle.net/yM9eiQ
有效:
https://dotnetfiddle.net/GhpF9X
using AutoMapper;
using AutoMapper.Configuration.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoMapperConsole1
{
[AutoMap(typeof(Person))]
class Employee
{
[SourceMember("FirstName")]
public string GivenName { get; set; }
[SourceMember("LastName")]
public string SurName { get; set; }
public decimal Salary { get; set; }
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
//http://automapper.readthedocs.io/en/latest/Getting-started.html
Person p = new Person();
p.FirstName = "John";
p.LastName = "Smith";
//Create a map
//Mapper.Initialize(cfg => cfg.CreateMap<Person, Employee>());
//or
var config = new MapperConfiguration(cfg => cfg.CreateMap<Person, Employee>());
//var mapper = config.CreateMapper();
//or
var mapper = new Mapper(config);
var dto = mapper.Map<Employee>(p);
//or
//Employee dto2 = Mapper.Map<Employee>(p);
Console.Write(dto.GivenName);
}
}
}
属性映射依赖于 AddMaps
完成的程序集扫描。对于给定的地图,属性映射和 CreateMap
是互斥的。但是你可以在相同的配置中拥有流畅的地图和属性地图。
为什么 Automapper 不使用 SourceMember 属性映射到 Employee?如果我将名称与名称相匹配:
无效:
https://dotnetfiddle.net/yM9eiQ
有效:
https://dotnetfiddle.net/GhpF9X
using AutoMapper;
using AutoMapper.Configuration.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoMapperConsole1
{
[AutoMap(typeof(Person))]
class Employee
{
[SourceMember("FirstName")]
public string GivenName { get; set; }
[SourceMember("LastName")]
public string SurName { get; set; }
public decimal Salary { get; set; }
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
//http://automapper.readthedocs.io/en/latest/Getting-started.html
Person p = new Person();
p.FirstName = "John";
p.LastName = "Smith";
//Create a map
//Mapper.Initialize(cfg => cfg.CreateMap<Person, Employee>());
//or
var config = new MapperConfiguration(cfg => cfg.CreateMap<Person, Employee>());
//var mapper = config.CreateMapper();
//or
var mapper = new Mapper(config);
var dto = mapper.Map<Employee>(p);
//or
//Employee dto2 = Mapper.Map<Employee>(p);
Console.Write(dto.GivenName);
}
}
}
属性映射依赖于 AddMaps
完成的程序集扫描。对于给定的地图,属性映射和 CreateMap
是互斥的。但是你可以在相同的配置中拥有流畅的地图和属性地图。