• linq to sql 扩展方法


          linq to sql 给我们带来很多惊奇的地方,减少我们的代码,节省了我们的时间,但是为了更方便做了一些小的扩展,部分内容来自网络。

          通过实体类插叙db.find<T>(T t):

      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)
                            {
                                if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj, null)) == 0)
                                {

                                }
                                else
                                {

                                  //构造linq 表达式
                                    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;
            }

          通过类的主键查询:

     public TEntity FindKey<TEntity>(object value) where TEntity : class
            {
                //获得所有property的信息
                PropertyInfo[] properties = typeof(TEntity).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 (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey)
                            {
                                ParameterExpression param = Expression.Parameter(typeof(TEntity), "d");
                                Expression right = Expression.Constant(value);
                                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);
                                break;

                            }


                        }
                    }
                }
                return query.First();
            }

        }

          通过实体类更新:

    public void Update<TEntity>(TEntity obj) where TEntity : class
            {
                string str = "update  [" + typeof(TEntity).Name + "] set ";
                string cols = "";
                string where="";
                //获得所有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)
                            {
                                if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey)
                                {
                                    where +=" where ["+p.Name+"]="+p.GetValue(obj,null);
                                }
                                else
                                {

                                    if (!(t.ToString().ToLower().Contains("string") || t.ToString().ToLower().Contains("datetime")))
                                        cols += "["+p.Name + "]=" + p.GetValue(obj, null) + ",";
                                    else
                                        cols += "["+p.Name + "]='" + p.GetValue(obj, null) + "',";
                                }
                            }
                        }
                    }
                }

                str += cols.Substring(0,cols.Length-1) +where;
                 HttpContext.Current.Response.Write("<br>"+str+"<br>");
                 this.ExecuteCommand(str);
             
            }
            public void UpdateAll<TEntity>(IEnumerable<TEntity> obj) where TEntity : class
            {
                foreach (var item in obj)
                {
                    this.Update<TEntity>(item);
                }
            }

      更新、删除、添加代码类似,也可以实现多条数据的数据操作。代码和更新类似。代码下载地址http://fccms.googlecode.com/files/linqtoaccess.rar 里面得db.cs文件里。

     
    ------------------------------------------------------------------------------------
    作者:王继坤

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    ------------------------------------------------------------------------------------
  • 相关阅读:
    【HYSBZ】1588 营业额统计
    【HYSBZ】1503 郁闷的出纳员
    【ZOJ】3228 Searching the String
    【ZOJ】3494 BCD Code
    【HDU】1754 I Hate It
    【HDU】3247 Resource Archiver
    【POJ】3481 Double Queue
    EdgeCore初学习
    go mod常用命令 已经 常见问题
    GO语言内存操作指导—unsafe的使用
  • 原文地址:https://www.cnblogs.com/wangjikun3/p/1508712.html
Copyright © 2020-2023  润新知