实体框架和自动化程序中的数据投影 [英] Data projection in Entity Framework and Automapper

查看:143
本文介绍了实体框架和自动化程序中的数据投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用AutoMapper构建一个在ASP.net MVC应用程序中使用的ViewModel(flattening - data projection)。

I want to use AutoMapper to construct a ViewModel (flattening - data projection) for use in an ASP.net MVC app.

var tmp = from x in db.Mailings select Mapper.Map<Mailing, MailingViewModel>(x);
return View(tmp.ToList());

当然,当我尝试上面的示例时,我得到了EF错误LINQ to Entities does not识别方法...方法,这种方法不能转换为存储表达式。

Of course, when I try the sample above, I get the EF error "LINQ to Entities does not recognize the method ... method, and this method cannot be translated into a store expression."

我知道可以在Automapper之前移动.ToList()它的魔法,但后来我从Db中获取所有的字段(我只需要20个字段中的3个)

I know it's possible to move the .ToList() before the Automapper does its magic, but then I fetch all the fields from the Db (and I only need 3 of 20 fields)

是否可以以干净的方式使用它。 Clean =不是所有的字段都是从数据库中获得的,而只是ViewModel所需的字段。是否可能在Automapper?还是其他图书馆? (不用手动))

Is it possible to use that in a clean way. Clean = Not all the fields are fetched from the DB, but only the fields necessary for the ViewModel. Is it possible in Automapper? Or perhaps an other library? (without doing it manually ;) )

推荐答案

是的,这是非常可能的。见 http://www.devtrends .co.uk / blog / stop-using-automapper-in-your-data-access-code

Yes this is very possible. See here http://www.devtrends.co.uk/blog/stop-using-automapper-in-your-data-access-code

编辑:我最近发现基础已经存在于AutoMapper中。为AutoMapper.QueryableExtensions添加一个using语句,并提供一个名为Project<>()的IQueryable扩展

I've recently found that the basis to this already exists in AutoMapper. add a using statement for AutoMapper.QueryableExtensions and you are provided with an IQueryable extension called Project<>()

这篇关于实体框架和自动化程序中的数据投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆