• dotnetcore EF 动态查询指定列


    普通情况下,可以通过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);
            }
    
  • 相关阅读:
    C语言中for循环的使用
    详解C语言的main函数
    计算机语言的发展(the history of computer's language)
    hdu 1001
    hoj 1002
    hdu 1000
    POJ 1000(水题)
    hoj 1001
    code hunt题解(1)
    《C和指针》学习笔记(3)
  • 原文地址:https://www.cnblogs.com/mryux/p/15863282.html
Copyright © 2020-2023  润新知