我知道可以使用LINQ将两种对象类型映射起来,方法是使用投影(projection):
var destModel = from m in sourceModel
select new DestModelType {A = m.A, C = m.C, E = m.E}
在哪里
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
}
我知道这很具有挑战性,但我希望这不是不可能的,因为这将为我节省大量模型和视图模型之间的显式映射工作。
propertyMap
和memberBindings
。 - Thomas Levesque