我有2个实体,国家和城市。一个国家可以有许多城市。 我想实现以下目标:
IQueryable<Country> query =
myContext.Countries
.Select(co => new Country
{
Id = co.Id,
Name = co.Name,
Cities = co.Cities.Select(c => new City { Id = c.Id, Name = c.Name })
})
.AsQueryable();
但是函数接受一个属性名称数组,如
string[] columns = new string[] { "Id", "Name", "Cities.Name" }
到目前为止,我尝试修改此平台上看到的以下功能,但它在&#34; Cities.Name&#34;上引发了异常。不属于国家实体。
public static IQueryable<TResult> Select<TResult>(this IQueryable source, string[] columns)
{
var sourceType = source.ElementType;
var resultType = typeof(TResult);
var parameter = Expression.Parameter(sourceType, "e");
var bindings = columns.Select(column => Expression.Bind(resultType.GetProperty(column), Expression.PropertyOrField(parameter, column)));
var body = Expression.MemberInit(Expression.New(resultType), bindings);
var selector = Expression.Lambda(body, parameter);
return source.Provider.CreateQuery<TResult>(
Expression.Call(typeof(Queryable), "Select", new Type[] { sourceType, resultType },
source.Expression, Expression.Quote(selector)));
}
呼叫:
IQueryable<Country> query = _hotelContext.Countries.Select<Country>(new string[] { "Id", "Name", "Cities.Name" });
return await query.ToListAsync();
请帮助,非常渴望得到答案。 干杯