普通情况下,可以通过select实现查询指定列,
ctx.Students.Select(s => new {s.Id, s.Name});
ctx.Students.Select(s => new object[] {s.Id, s.Name});
这里使用动态方式实现select查询指定列
using (MyDbContext ctx = new MyDbContext())
{
var students = Query<Student>(ctx, "Id", "Name");
foreach (object[] s in students)
{
Console.WriteLine(s[0] + "," + s[1]);
}
}
static IEnumerable<object[]> Query<T>(MyDbContext ctx, params string[] propertyNames)
where T : class
{
var p = Parameter(typeof(T));
List<Expression> propExprList = new List<Expression>();
foreach (string propertyName in propertyNames)
{
Expression propExpr = Convert(MakeMemberAccess(p, typeof(T).GetProperty(propertyName)), typeof(object));
propExprList.Add(propExpr);
}
var newArrayExpr = NewArrayInit(typeof(object), propExprList.ToArray());
var selectExpr = Lambda<Func<T, object[]>>(newArrayExpr, p);
return ctx.Set<T>().Select(selectExpr);
}
---------------------------
知道的更多,不知道的也更多
---------------------------