本文介绍了使用LINQ动态绘制地图(或构建投影)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以使用LINQ使用投影映射两种对象类型,如下所示:
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
}
我知道这很有挑战性,但我希望这不是不可能的,因为它将为我节省大量模型和视图模型之间的显式映射工作。
推荐答案
您必须生成表达式树,但是很简单,所以不是很难.
void Main()
{
var source = new[]
{
new SourceModelType { A = "hello", B = "world", C = "foo", D = "bar", E = "Baz" },
new SourceModelType { A = "The", B = "answer", C = "is", D = "42", E = "!" }
};
var dest = ProjectionMap<SourceModelType, DestModelType>(source.AsQueryable());
dest.Dump();
}
public static IQueryable<TDest> ProjectionMap<TSource, TDest>(IQueryable<TSource> sourceModel)
where TDest : new()
{
var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);
var destProperties = typeof(TDest).GetProperties().Where(p => p.CanWrite);
var propertyMap = from d in destProperties
join s in sourceProperties on new { d.Name, d.PropertyType } equals new { s.Name, s.PropertyType }
select new { Source = s, Dest = d };
var itemParam = Expression.Parameter(typeof(TSource), "item");
var memberBindings = propertyMap.Select(p => (MemberBinding)Expression.Bind(p.Dest, Expression.Property(itemParam, p.Source)));
var newExpression = Expression.New(typeof(TDest));
var memberInitExpression = Expression.MemberInit(newExpression, memberBindings);
var projection = Expression.Lambda<Func<TSource, TDest>>(memberInitExpression, itemParam);
projection.Dump();
return sourceModel.Select(projection);
}
(在LinqPad中测试,因此Dump
%s)
生成的投影表达式如下:
item => new DestModelType() {A = item.A, C = item.C, E = item.E}
这篇关于使用LINQ动态绘制地图(或构建投影)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!