转换的IQueryable< T>反对另一个对象? [英] Converting IQueryable<T> object to another object?

查看:156
本文介绍了转换的IQueryable< T>反对另一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道的关键字所以这里究竟是什么,我希望有一个例子:

I have no idea what the keywords are so here is an example of what I want:

return from i in userRepo.GetUsers()
  select new SimpleUser{
        i.UserId,
        i.Name
  };

userRepo.GetUsers()返回类型为的IQueryable<使用者> 。我想将其转换为的IQueryable< SimpleUser> 来,我可以限制访问用户的某些属性

userRepo.GetUsers() returns type IQueryable<User>. I'd like to convert this to IQueryable<SimpleUser> to I can restrict access to certain properties of the User domain.

我如何做到这一点没有硬编码的转换也是这样吗?什么样automapper或ValueInjecter工具,他们怎么能做到这一点?

How do I do this without hard coding the translation like this? What about tools like automapper or ValueInjecter, how can they do this?

此外,什么是所谓的这种技术?

Also, what is this technique called?

推荐答案

您必须硬code编译或你必须先将其转换为的IEnumerable 的IQueryable 重presents EX pression树转换到使用提供一些执行 - 在你的情况下,我相信这将是实体框架。您不能使用任何自动映射在这样的查询,因为它会被转换为SQL,不会理解你的.NET方法或AutoMapper。预测到自定义类型是查询的一部分,必须硬codeD。您可以创建自定义的扩展方法的IQueryable 并重新使用它,你需要:

You must hardcode the translation or you must first convert it to IEnumerable. IQueryable represents expression tree translated to some execution in used provider - in your case I believe it will be Entity framework. You can't use any automatic mapping in such query because it will be translated to SQL which will not understand your .net methods or AutoMapper. Projections to custom types are part of the query and must be hardcoded. You can create custom extension method to IQueryable and reuse it where you need:

public static IQueryabe<SimpleUser> ProjectToSimpleUser(this IQueryable<User> query)
{
    return query.Select(u => new SimpleUser
        {
            // Here map your fields
        });
}

现在你可以使用:

return repo.GetUsers().ProjectToSimpleUser();

在案件实体框架 SimpleUser 不能是映射的实体。

In case of Entity framework SimpleUser mustn't be an mapped entity.

这篇关于转换的IQueryable&LT; T&GT;反对另一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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