[英]Select query on type to transform it into its sub type using Linq
I am working on a ASP.Net core project, and i have a model as below : 我正在研究ASP.Net核心项目,并且我有一个如下模型:
Class abcde
{
int a {get;set;}
int b {get;set;}
int c {get;set;}
int d {get;set;}
int d {get;set;}
}
In a particular view i just required properties a and b of the above defined model. 在特定视图中,我只需要上述定义的模型的属性a和b。 So, i just define a ViewModel class (into a different namespace) as below :
因此,我只定义了一个ViewModel类(放入另一个名称空间),如下所示:
Class ab
{
int a {get;set;}
int b {get;set;}
}
Now in the controller i am making a select query, and i intend to select only a and b properties. 现在在控制器中,我正在进行选择查询,我打算仅选择a和b属性。 As these are the only properties i want to show in the view.
因为这些是我要在视图中显示的唯一属性。 So, basically my query must be :
因此,基本上我的查询必须是:
var objects = _context.abcde.Select( x=> new {x.a, x.b}).ToArray()
The problem here is that i get a Array of an anonymous type, which i need to map manually to my viewmodel class ab. 这里的问题是我得到了一个匿名类型的数组,我需要手动将其映射到我的viewmodel类ab。 In this case, i will have to have a loop to manually transform each of the result-set into the ViewModel.
在这种情况下,我必须要有一个循环才能将每个结果集手动转换为ViewModel。
Looking at the signature of Select function 查看Select函数的签名
Enumerable.Select TSource, TResult
可枚举选择TSource,TResult
It appears, that the function itself can do the transformation, but i couldn't find any examples. 看来,函数本身可以完成转换,但是我找不到任何示例。 I might be having a wrong thought here.
我在这里可能有一个错误的想法。 Can you please suggest the way to handle such a scenario.
您能否建议处理这种情况的方法。 I believe this is going to be very common case.
我相信这将是非常普遍的情况。 Thanks in advance.
提前致谢。
The problem here is that i get a Array of an anonymous type, which i need to map manually to my viewmodel class ab.
这里的问题是我得到了一个匿名类型的数组,我需要手动将其映射到我的viewmodel类ab。 In this case, i will have to have a loop to manually transform each of the result-set into the ViewModel.
在这种情况下,我必须要有一个循环才能将每个结果集手动转换为ViewModel。
So just project using the ab
class by using it like this: 因此,只需像这样使用
ab
类来投影即可:
x => new ab() { a = x.a, b = x.b }
Instead of using anonymous type: 而不是使用匿名类型:
x => new { x.a, x.b }
So your final query will look like below: 因此,您的最终查询将如下所示:
var objects = _context.abcde.Select(x => new ab { a = x.a, b = x.b }).ToArray()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.