我们正在尝试投射一个实例IQueryable<EntityObject>
to an IQueryable<SpecificEntityObject>
, the SpecificEntityObject
类型仅在运行时才知道。
我们尝试使用下面的代码,但该代码无法编译,因为类型或命名空间“objType”不存在。
var t = query.ElementType;
Type objType = typeof(IQueryable<>).MakeGenericType(t);
var typed = query.Cast<IEnumerable<objType>>();
var grouped = typed.GroupByMany(groupBy.Select(grp => grp.Expression).ToArray());
有任何想法吗?
使用以下 IQueryable 扩展通用方法query.ToDTO<sourceType,DestType>();
:
public static class QueryableExtensions
{
public static IQueryable<TDest> ToDTO<TSource, TDest>(this IQueryable<TSource> source)
{
List<TDest> destinationList = new List<TDest>();
List<TSource> sourceList = source.ToList<TSource>();
var sourceType = typeof(TSource);
var destType = typeof(TDest);
foreach (TSource sourceElement in sourceList)
{
TDest destElement = Activator.CreateInstance<TDest>();
//Get all properties from the object
PropertyInfo[] sourceProperties = typeof(TSource).GetProperties();
foreach (PropertyInfo sourceProperty in sourceProperties)
{
//and assign value to each propery according to property name.
PropertyInfo destProperty = destType.GetProperty(sourceProperty.Name);
destProperty.SetValue(destElement, sourceProperty.GetValue(sourceElement, null), null);
}
destinationList.Add(destElement);
}
return destinationList.AsQueryable();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)