【问题标题】:Automapper with c#使用 C# 的自动映射器
【发布时间】:2018-10-20 23:04:14
【问题描述】:

我正在尝试使用 automapper 提高我的 api 的性能。我已经创建了目标 DTO,并且我已经有一个源 mnodel。我也创建了映射,但是当我映射此错误时。

 The type arguments for method 'Enumerable.Select<TSource, TResult> 
 (IEnumerable<TSource>, Func<TSource, TResult>)' cannot be inferred from the 
 usage. Try specifying the type arguments explicitly.

查看下面的代码示例

  [Route("StaffInfo/{*job_title}")]
    public IHttpActionResult GetStaffInfoByTitle(string job_title)
    {

        var rStructure = _context.employeeinfo.Where(e => e.jobtitle.Contains(job_title)).ToList()
                         .Select(Mapper.Map<employeeinfo, employeeinfoDto>);




        if (rStructure == null)
        {
            return NotFound();
        }

        return Ok(rStructure);
    }

DTO 模型

    public class employeeinfoDto
   {
    public string employee_number { get; set; }
    public string name { get; set; }
    public string companyname { get; set; }
    public int employee_id { get; set; }
    public Byte? linemanager { get; set; }
   }

Domian 模型

    public class employeeinfo
    {  
     public string employee_number { get; set; }
     public string name { get; set; }
     public string companyname { get; set; }
     public int employee_id { get; set; }
     public Byte? linemanager { get; set; }
    }

映射配置文件

  Mapper.CreateMap<employeeinfo, employeeinfoDto>();

【问题讨论】:

  • 答案在错误中。或者尝试指定一个 lambda。
  • 但我正在使用 automapper,它应该会自动执行此操作吗?
  • “提高性能”不是 automapper 的主张之一。增加/尊重什么?手动复制总是最快的。
  • @gbubemismith 应该这样,所以类型不是你期望的那样。 IE。 new List&lt;employeeinfo&gt;().Select(Mapper.Map&lt;employeeinfo, employeeinfoDto&gt;) 对我来说似乎工作得很好。指定类型或 lambda 将揭示潜在问题。
  • 是的,检查你的所有假设。您可能已经创建了一个新类,而不是在某处添加 using,Ctrl+. 会这样做。

标签: c# entity-framework rest asp.net-web-api automapper


【解决方案1】:

您可以像这样使用可查询扩展:

var rStructure = _context.employeeinfo.Where(e => e.jobtitle.Contains(job_title))
                     .ProjectTo<employeeinfoDto>().ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2021-10-28
    • 2015-12-13
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多