Billpeng Space

技术源自生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

sql to linq的常用代码

Posted on 2010-07-19 21:12  billpeng  阅读(213)  评论(0编辑  收藏  举报

添加记录
1、添加一条新纪录(例如:添加一条新闻)
    public static void addNewsInfo(NewsInfo entity)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            db.NewsInfo.InsertOnSubmit(entity);
            db.SubmitChanges();
        }
    }

修改信息
1、修改一条纪录(例如:更新新闻)
    public static void updateNewsInfo(NewsInfo entity)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            var temp = db.NewsInfo.Where(w => w.NewsID == entity.NewsID).SingleOrDefault();
            if (temp != null)
            {
                temp.Title = entity.Title;
                temp.SubTitle=entity.SubTitle;
                temp.Source = entity.Source;
                temp.Author = entity.Author;
                temp.ClassID = entity.ClassID;
                temp.Summary = entity.Summary;
                temp.NewsDate = entity.NewsDate;
                temp.Content = entity.Content;

                db.SubmitChanges();
            }
        }
    }

2、更新多条记 录(例如:将某个栏目的新闻作者统一更新,这种方式不好,建议在linq中 调用存储过程。直接把存储过程拖到linq to sql就可以当做方法来调用。
    public static void updateNewsByClassID(int classid,string author)
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = db.NewsInfo.Where(w => w.ClassID == classid);
            foreach (var temp in query)
            {
                temp.Author = author;
            }
            db.SubmitChanges();
        }
    }

删除记录
1、 删除一条记录(指定主键)(例如:根据新闻的ID删除新闻)
    public static void deleteNewsInfo(int newsID)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            var temp = db.NewsInfo.Where(w => w.NewsID == newsID).SingleOrDefault();
            if (temp != null)
            {
                db.NewsInfo.DeleteOnSubmit(temp);
                db.SubmitChanges();
            }
        }
    }

2、批量删除数据(指定主键数组)(例如:多选框选择新闻ID来删除新闻)
    public static void deleteNewsInfo(int[] newsID)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            var list = db.NewsInfo.Where(w => newsID.Contains(w.NewsID));
            db.NewsInfo.DeleteAllOnSubmit(list.ToList());
            db.SubmitChanges();
        }
    }

3、删除符合指定条件的数据(无、一条、多条)(例 如:删除某个类别的新闻)
    public static void delNewsByClassID(int classid)
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = db.NewsInfo.Where(w => w.ClassID == classid);
            db.NewsInfo.DeleteAllOnSubmit(query);
            db.SubmitChanges();
        }
    }

4、上面的删除多条记录是需要先把要删除的信息先 查询出来,然后再提交删除,看看老赵扩展的批量删除功能,用起来就方便多了。
http://www.cnblogs.com/JeffreyZhao/archive/2008/03/05/LINQ-to-SQL-Batch-Delete-Extension.html

获 取数据
1、获取一条数据的详细信息(指定主键)(例如:根据新闻的ID来获取新闻内容)
public static NewsInfo getNewsInfoDetail(int newsID)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            var temp = db.NewsInfo.Where(w => w.NewsID == newsID).SingleOrDefault();
            return temp;
        }
    }

2、获取指定条件的记录(classID=0时,不加条件筛选)  (例如:获取某个栏目的新闻信息,一般数量不多的使用,多的就用分 页或者指定取的数量)  
public static List<NewsInfo> getNewsInfo(int classID)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
                var query = from temp in db.NewsInfo
                            where ((classID == 0) || (temp.ClassID == classID))
                            orderby temp.IsTop descending, temp.NewsDate descending
                            select temp;
                return query.ToList();  
        }
    }

3、获取指定条件的几条记录(一般都要加上排序规则)(例如:提取最新的3条行业新闻)
    public static List<NewsInfo> getImageNewsInfo(int classID, int topNum)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
                var query = (from temp in db.NewsInfo
                            where ((classID == 0) || (temp.ClassID == classID))
                            orderby temp.IsTop descending, temp.NewsDate descending
                            select temp).Take(topNum);

                return query.ToList();     
        }
    }

4、获取分页记录(排序规则是必须的)(例如:最 常见的新闻分页,带点条件搜索,根据标题或者新闻栏目)
    public static List<NewsInfo> getNewsInfoList(string title, int classID, int curpage, int pagesize, out int records)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            records = (from temp in db.NewsInfo
                       where ((classID == 0) || (temp.ClassID == classID))
                       && SqlMethods.Like(temp.Title, "%" + title + "%")
                       select temp.NewsID).Count();

            int takes = curpage * pagesize;
            int skips = (curpage - 1) * pagesize;

            var query = (from temp in db.NewsInfo
                         where ((classID == 0) || (temp.ClassID == classID))
                         && SqlMethods.Like(temp.Title, "%" + title + "%")
                         orderby temp.NewsDate descending, temp.CreateDate descending
                         select temp).Take(takes).Skip(skips);
           
            return query.ToList();
        }
    }

5、使用join处理多个表的数据联合(例 如:显示指定新闻分类名称的新闻,NewsInfo默认记录分类的ID)
只输入一个表里的信息,在List后面可以明确对象
    public static List<NewsInfo> getNewsList(string className)
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = from temp1 in db.NewsInfo
                        join temp2 in db.ClassInfo
                        on temp1.ClassID equals temp2.ClassID
                        where temp2.ClassName == className
                        select temp1;
         
            return query.ToList();
        }
    }

如果要输出两个表或者多个表里的字段,那 就需要使用匿名类,或者重新定义一个输出对象(继承某个表,然后加几个缺少的字段)
    public static List<Object> getNewsList(int classID)
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = from temp1 in db.NewsInfo
                        join temp2 in db.ClassInfo
                        on temp1.ClassID equals temp2.ClassID
                        where temp1.ClassID == classID
                        select new
                        {
                            NewsID=temp1.NewsID,
                            Title=temp1.Title,
                            ClassName=temp2.ClassName,
                            Content=temp1.Content
                        };

            //下面这块是不得以而为之,匿名类不允许隐式转换为 object对象。如果你直接在aspx.cs文件里使用,那就不存在这种问题。
            List<object> list = new List<object>();
            foreach (var o in query.ToList())
            {
                list.Add(o);
            }

            return list;
        }
    }

6、如果表之间本身就存在外键关系,在linq里的表对象自动会关 联,这种关联在多表查询的时候更方便。
假设有表一:NewsInfo(字段:NewsID,Title,ClassID,Content)  表二:ClassInfo(ClassID,ClassName)
表二的ClassID是表一的ClassID的外键(在sql里建立二者之间的 外键关系)


   public static List<NewsInfo> getNewsByClassName(string className)
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = from temp in db.NewsInfo
                        where temp.ClassInfo.ClassName == className
                        select temp;

            return query.ToList();
        }
    }

7、linq使用嵌套查询(还是上面新闻和新 闻栏目的表结构)
    public static List<NewsInfo> getNewsByClassN(string className)
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = from temp in db.NewsInfo
                        where temp.ClassID == (from temp1 in db.ClassInfo
                                               where temp1.ClassName == className
                                               select temp1).Single().ClassID
                        select temp;
            return query.ToList();
        }
    }

8、结合匿名类来实现投影查询(有外键关 联,例如:统计所有新闻分类的总浏览次数[分类下面新闻的浏览次数总和])
    public static List<Object> getNewsClassStat()
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            var query = from temp in db.ClassInfo
                        select new
                        {
                            ClassID=temp.ClassID,
                            ClassName=temp.ClassName,
                            ViewNum=temp.NewsInfo.Sum(w=>w.ViewNum)
                        };
            List<object> list = new List<object>();
            foreach (var o in query.ToList())
            {
                list.Add(o);
            }
            return list;
        }
    }

9、linq的扩展查询方法(Average、Count、Sum、Max、Min等)
    public static int getNewsAvView()
    {
        using (SiteCmsDataContext db = new SiteCmsDataContext())
        {
            int avView =(int) db.NewsInfo.Average(w => w.ViewNum);
            return avView;
        }
    }

其他:
1、获取新插入记录的自增长ID(例如:在注册完之后就自动登 录,需要用到自增长字段来设置session等)
 public static int addNewsInfo(NewsInfo entity)
    {
        using (SiteCMSDataContext db = new SiteCMSDataContext())
        {
            db.NewsInfo.InsertOnSubmit(entity);
            db.SubmitChanges();
             int newsID=entity.NewsID;
             return newsID;
        }
    }