将IQueryable <EntityObject>转换为IQueryable <Specific>

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)

有任何想法吗?

Nit*_*ant 7

使用以下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)

  • 奇怪的是OP接受了这个作为答案。她不仅在编译时没有“TDest”,而且这种方法会急切地将所有内容加载到内存中,这会消耗大量数据。 (2认同)