我有一个由另一个类继承的基类:
class Base { }
class Derived : Base { }
实体框架仅存储派生类的实例。我想只选择与基类中的字段对应的列,并将它们返回为IEnumerable<Base>
。有一个简单的方法吗?
答案 0 :(得分:2)
实际上,只要John Appleseed
类型不被EF识别为实体(因为某些原因它不允许投影到实体类型),您可以使用以下简单帮助器从我对c# How can I create a collection of custom objects without going through each field的回答:
Base
像这样:
public static class QueryableExtensions
{
public static IQueryable<TResult> SelectTo<TResult>(this IQueryable source)
{
var sourceType = source.ElementType;
var resultType = typeof(TResult);
var parameter = Expression.Parameter(sourceType, "x");
var bindings =
from rm in resultType.GetProperties().Concat<MemberInfo>(resultType.GetFields())
join sm in sourceType.GetProperties().Concat<MemberInfo>(sourceType.GetFields())
on rm.Name equals sm.Name
select Expression.Bind(rm, Expression.MakeMemberAccess(parameter, sm));
var body = Expression.MemberInit(Expression.New(resultType), bindings);
return source.Provider.CreateQuery<TResult>(Expression.Call(
typeof(Queryable), "Select", new[] { sourceType, resultType },
source.Expression, Expression.Quote(Expression.Lambda(body, parameter))));
}
}