IQueryable Lambda Projection Syntax

跟風遠走 提交于 2019-12-03 14:54:09

What is the appropriate syntax to create a IQueryable projection using Automapper?

There isn't one. Automapper doesn't do this. It's the wrong tool for this job.

One could create an Automapper-like tool to do a similar thing for query projections. I've considered it in the past, but always concluded that code using it would be less readable than the projection. I don't want to optimize code-writing time over code-reading time.

Your updated code doesn't work because it isn't an expression. If you do:

private static Expression<Func<Client, ClientP>> ClientP ClientToClientP()
{
    return c => new ClientP { Id = c.Id, FirstName = c.FirstName };
}

...and then:

IQueryable<Client> originalModel = repo.QueryAll();
Expression<Func<Client, ClientP>> exp = ClientToClientP();
IQueryable<ClientP> projection = originalModel.Select(exp);

...then it will work.

This has actually been solved now by the author of AutoMapper here: http://lostechies.com/jimmybogard/2011/02/09/autoprojecting-linq-queries/

He provides an implementation that takes a desired projection and the query and queries the database for only the fields needed for the projection mapping.

Also, see the follow-on article by Paul Hiles for some caching improvements.

Hope this helps.

If you add .ToList() before the Select you can force the mapping to happen client-side (Linq to Objects) instead of server side (SQL). Just make sure you've done your filtering first so you aren't bringing the whole table over.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!