我已经在c#中编写了一个程序并使用了者自动映射。我使用了Null替换,但它没有替换结果中的给定值我只得到null。请检查下面的代码。我想要我的结果显示8099000078
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Automapper;
namespace Automapper
{
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
}
public class Patient
{
public string Name { get; set; }
public string Location { get; set; }
public int age { get; set; }
public string phone { get; set; }
static void Main(string[] args)
{
User obj = new User();
obj.FirstName = "sujit";
obj.LastName = "kumar";
obj.Address = "Bangalore";
obj.Mobile = "";
AutoMapper.Mapper.CreateMap<User, Patient>().ForMember(
emp => emp.Name, map => map.MapFrom(p => p.FirstName + " " + p.LastName))
.ForMember(dest => dest.Location, source => source.MapFrom(x => x.Address))
.ForMember(dest => dest.phone, source => source.NullSubstitute("8099000078"));
var result = AutoMapper.Mapper.Map<User, Patient>(obj);
// Console.WriteLine(result.Name);
// Console.WriteLine(result.Location);
Console.WriteLine(result.phone);
Console.ReadLine();
}
}
}
答案 0 :(得分:2)
你错过了null替代品的工作方式。
空替换允许您为a提供备用值 目标成员,如果源值在任何地方为null 成员链。
在您的代码中,您没有为phone
属性提供任何来源,因此它没有任何值来检查null并且它不执行空替换。
我对您的代码进行了一些更改以使其正常工作(请参阅下文):
void Main()
{
User obj = new User();
obj.FirstName = "sujit";
obj.LastName = "kumar";
obj.Address = "Bangalore";
obj.Mobile = null;
var config = new MapperConfiguration(cfg => cfg.CreateMap<User, Patient>()
.ForMember(emp => emp.Name, map => map.MapFrom(p => p.FirstName + " " + p.LastName))
.ForMember(dest => dest.Location, source => source.MapFrom(x => x.Address))
.ForMember(dest => dest.phone, source => source.MapFrom(x => x.Mobile))
.ForMember(dest => dest.phone, source => source.NullSubstitute("8099000078")));
var mapper = config.CreateMapper();
var result = mapper.Map<User, Patient>(obj);
result.Dump();
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
}
public class Patient
{
public string Name { get; set; }
public string Location { get; set; }
public int age { get; set; }
public string phone { get; set; }
}
在这里,我提供了phone
属性的来源(我从Mobile
映射了它)并设置了null
值。
答案 1 :(得分:1)
这应该有效 -
sudo apt-cache madison ^apache2
答案 2 :(得分:0)
之前我没有使用过Automapper,但是看看你的语法,看来'source'永远不会为null,因为你传递了一个有效的obj(因此永远不会让NullSubstitute()返回8099000078.
我看不到你要映射的地方dest =&gt; dest.phone,source =&gt; source.Mobile。