LINQ和AutoMapper [英] LINQ and AutoMapper

查看:1002
本文介绍了LINQ和AutoMapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有什么我可以做有望得到这个工作。这在我的代码工作正常:;角色>()

I'm wondering if there is anything I can do to get this working as expected. This works fine in my code:

        var roles = _securityContext.Set<Role>();
        var roleList = new List<RoleDto>();
        foreach (var role in roles)
        {
            roleList.Add(Mapper.Map<Role, RoleDto>(role)); 
        }

        return roleList;



不过把这个选项改为:

But changing this to:

        var roles = _securityContext.Set<Role>();

        return roles.Select(role => Mapper.Map<Role, RoleDto>(role)).ToList();



结果我从来没见过的:

Results in an error I've not seen before:

LINQ到实体无​​法识别方法Security.Dto.RoleDto MapRole,RoleDto的方法,而这种方法不能被翻译成店表达

"LINQ to Entities does not recognize the method 'Security.Dto.RoleDto MapRole,RoleDto' method, and this method cannot be translated into a store expression"

我不知道如果我甚至可以做this'problem什么...可以说,工程的方法更可读反正...

I'm not sure if I can even do anything about this'problem' ... arguably the method that works is more readable anyway ...

推荐答案

您正在对的IQueryable ,它试图将你供到SQL方法操作。显然,这是不会发生的,因为你传递AutoMapper相关的魔力。这里有一个简单的解决方案,你必须映射之前强制执行:

You're operating on IQueryable, which tries to translate the method you supply into SQL. Obviously, it's not going to happen, as you're passing AutoMapper related magic. There's an easy solution, you have to force execution before mapping:

return roles.ToList().Select(role => Mapper.Map<Role, RoleDto>(role)).ToList();

正如丹尼尔暗示的意见,你总是可以从 IQueryable的去的IEnumerable 致电 AsEnumerable(),仍然推迟执行:

As Daniel suggests in comments, you can always go from IQueryable to IEnumerable by calling AsEnumerable() and still defer execution:

return roles.AsEnumerable().Select(role => Mapper.Map<Role, RoleDto>(role)).ToList();

这篇关于LINQ和AutoMapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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