Stu*_*nar 11 c# linq entity-framework casting iqueryable
我们正在尝试将一个实例转换IQueryable<EntityObject>
为a IQueryable<SpecificEntityObject>
,该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());
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
使用以下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();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9280 次 |
最近记录: |