How can I convert Linq results to DTO class object without iteration

前端 未结 4 1525
忘了有多久
忘了有多久 2020-12-24 14:07

I\'m building a Web API project that will be made available to third-party\'s and also used by my own web application/s. The Web API methods will return JSON representations

4条回答
  •  梦谈多话
    2020-12-24 14:20

    We can get really compact if we use AutoMapper.

    Bootstrap the mapper in your repository:

    Mapper.CreateMap();

    Then it's pretty simple (and there's nothing wrong with returning IEnumerable).

    public IEnumerable Get()
    {
        using (var db = new MyContext())
        {
            return (from u in db.Users
                    orderby u.FirstName
                    select Mapper.Map(u)).AsEnumerable();
        }
    }
    

提交回复
热议问题