• Linq 通过反射动态查询对象


    public IQueryable<TEntity> Find<TEntity>(TEntity obj) where TEntity : class
            
    {
                
    //获得所有property的信息
                PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public |
     BindingFlags.Instance);
                
    //构造初始的query
                IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();
                
    //遍历每个property
                foreach (PropertyInfo p in properties)
                
    {
                    
    if (p != null)
                    
    {
                        Type t 
    = p.PropertyType;
                        
    //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。
                        if (t.IsValueType || t == typeof(string|| t == typeof(System.Byte[])
                            
    || t == typeof(object|| t == typeof(System.Xml.Linq.XDocument)
                            
    || t == typeof(System.Data.Linq.Binary))
                        
    {
                            
    //如果不为null才算做条件
                            if ( p.GetValue(obj, null!= null)
                            
    {
                                ParameterExpression param 
    = Expression.Parameter(typeof(TEntity), "c");
                                Expression right 
    = Expression.Constant(p.GetValue(obj, null));
                                Expression left 
    = Expression.Property(param, p.Name);
                                Expression filter 
    = Expression.Equal(left,right);

                                Expression
    <Func<TEntity, bool>> pred = Expression.Lambda<Func
    <
    TEntity, bool>>(filter, param);
                                query 
    = query.Where(pred);
                            }

                        }

                    }

                }

                
    return query;
            }

    调用:

                Customer c = new Customer();
                c.City 
    = "London";
                c.Phone 
    = "23236133";

                var q 
    = db.Find<Customer>(c).ToList();


    关于作者: 王昕(QQ:475660) 在广州工作生活30余年。十多年开发经验,在Java、即时通讯、NoSQL、BPM、大数据等领域较有经验。
    目前维护的开源产品:https://gitee.com/475660
  • 相关阅读:
    C#基础篇十小练习
    C#基础篇九OOP属性结构枚举
    C#基础篇八构造函数和面向对象思想
    C#基础篇七类和静态成员
    C#基础篇六飞行棋
    C#基础篇五值类型和引用类型
    数据与地址的自动给定---基于状态机
    SPI 核的寄存器空间
    mig_7series DDR控制器的配置
    关于zynq7 中MIO的理解
  • 原文地址:https://www.cnblogs.com/starcrm/p/1362350.html
Copyright © 2020-2023  润新知