我目前在我的 c# MVC 项目中使用 AutoMapper,并且遇到了从整数转换为字符串的问题。
我有两节课:
public class Job
{
public string Prefix { get; set; }
public int JobNumber { get; set; }
public int Year { get; set }
public int JobPriority { get; set; }
public virtual EntityPriority EntityPriority { get; set; }
}
public class JobViewModel
{
public string JobNumberFull { get; set; }
{
使用 Automapper 我想加入 Job 类中的所有三个属性以形成一个字符串,然后将其映射到 JobViewModel 类中的 JobNumberFull。:
前缀-JobNumber-Year
首先,我保持简单,没有将字段连接成字符串,我只是尝试获取 JobNumber (int) 并将其映射到 JobNumberFull (string),如下所示:
Mapper.CreateMap<int, string>().ConvertUsing(Convert.ToString);
Mapper.CreateMap<Job, JobViewModel>()
.ForMember(d => d.JobPriorityId, opt => opt.MapFrom(s => s.EntityPriority.EntityPriorityID))
.ForMember(d => d.JobPriorityLevel, opt => opt.MapFrom(s => s.EntityPriority.PriorityLevel))
.ForMember(d => d.JobNumberFull, opt => opt.MapFrom(s => s.JobNumberYear));
Mapper.AssertConfigurationIsValid();
var jobsList = db.Jobs.Where(j => j.OperationID == operationId).Project().To<JobViewModel>().ToList();
当我运行它时,我收到以下错误
Type 'System.String' does not have a default constructor
我知道这与
Convert.ToString
但我不知道该怎么办!从字符串转换为 int 时,我可以执行 Convert.ToInt32 ,它就像一种享受。我需要创建自定义类型转换器吗?
我将如何获取字符串 prefix-jobnumber-year?
非常感谢所有帮助。
更新
多亏了 Jeremy 和 AutoMapper 网站的帮助,我才得以在这里工作,这是我的解决方案,如果您认为有更优雅的解决方案,请随时发表评论:
public class Job
{
public string Prefix { get; set; }
public int JobNumber { get; set; }
public int Year { get; set; }
public int JobPriority { get; set; }
public virtual EntityPriority EntityPriority { get; set; }
}
public class JobViewModel
{
public int JobNumber { get; set; }
public int Year { get; set; }
public string JobNumberFull { get; set; }
}
public enum EntityPriority
{
Normal = 0,
High
}
public interface IValueResolver
{
ResolutionResult Resolve(ResolutionResult source);
}
public class JobNumberConverter : ValueResolver<Job, string>
{
protected override string ResolveCore(Job source)
{
return string.Format("{0}-{1}-{2}", source.Prefix, source.JobNumber, source.Year);
}
}
public ActionResult Index()
{
Mapper.CreateMap<Job, JobViewModel>()
.ForMember(jvm => jvm.JobNumberFull, opt => opt.ResolveUsing<JobNumberConverter>());
Mapper.AssertConfigurationIsValid();
List<Job> jobs = new List<Job>();
Job j = new Job()
{
JobNumber = 1,
Prefix = "prefix",
Year = 2013,
EntityPriority = EntityPriority.High,
JobPriority = 2
};
Job j2 = new Job()
{
JobNumber = 2,
Prefix = "prefix",
Year = 2013,
EntityPriority = EntityPriority.High,
JobPriority = 2
};
Job j3 = new Job()
{
JobNumber = 3,
Prefix = "prefix",
Year = 2013,
EntityPriority = EntityPriority.High,
JobPriority = 2
};
jobs.Add(j);
jobs.Add(j2);
jobs.Add(j3);
var jobViewModels = jobs.Select(job => Mapper.Map<JobViewModel>(job));
return View();
}