使用 LINQ 动态映射(或构造投影)
我知道我可以使用投影通过 LINQ 映射两种对象类型,如下所示:
var destModel = from m in sourceModel
select new DestModelType {A = m.A, C = m.C, E = m.E}
where
class SourceModelType
{
string A {get; set;}
string B {get; set;}
string C {get; set;}
string D {get; set;}
string E {get; set;}
}
class DestModelType
{
string A {get; set;}
string C {get; set;}
string E {get; set;}
}
但是,如果我想要制作类似泛型的东西来执行此操作,而我具体不知道我正在处理的两种类型,该怎么办?所以它会遍历“Dest”类型并与匹配的“Source”类型匹配......这可能吗?另外,为了实现延迟执行,我希望它只返回一个 IQueryable。
例如:
public IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
{
// dynamically build the LINQ projection based on the properties in TDest
// return the IQueryable containing the constructed projection
}
我知道这很有挑战性,但我希望不是不可能,因为这将为我节省模型和视图模型之间的大量显式映射工作。
I know I can map two object types with LINQ using a projection as so:
var destModel = from m in sourceModel
select new DestModelType {A = m.A, C = m.C, E = m.E}
where
class SourceModelType
{
string A {get; set;}
string B {get; set;}
string C {get; set;}
string D {get; set;}
string E {get; set;}
}
class DestModelType
{
string A {get; set;}
string C {get; set;}
string E {get; set;}
}
But what if I want to make something like a generic to do this, where I don't know specifically the two types I am dealing with. So it would walk the "Dest" type and match with the matching "Source" types.. is this possible? Also, to achieve deferred execution, I would want it just to return an IQueryable.
For example:
public IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
{
// dynamically build the LINQ projection based on the properties in TDest
// return the IQueryable containing the constructed projection
}
I know this is challenging, but I hope not impossible, because it will save me a bunch of explicit mapping work between models and viewmodels.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须生成一个表达式树,但是是一个简单的表达式树,所以它并不难...
(在 LinqPad 中测试,因此是
Dump
s)生成的投影表达式如下所示:
You have to generate an expression tree, but a simple one, so it's not so hard...
(tested in LinqPad, hence the
Dump
s)The generated projection expression looks like that :