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();
總結
以上是生活随笔為你收集整理的Linq 通过反射动态查询对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 星际战甲国际服暗影圣剑怎么获得
- 下一篇: QT安装以及使用(QT支持linux和w