Linq To sql入门练习

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 练习LinQ入门
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private mydbDataContext context = new mydbDataContext();

        private void Form1_Load(object sender, EventArgs e)
        {
            FillInfo();
            cbx_sex.SelectedIndex = 0;
        }

        private void FillInfo()
        {
            //法一:
            //List<Info> list = context.Info.ToList();
            //dataGridView1.DataSource = list;
            //法二:
            //var query = from p in context.Info select p;
            //dataGridView1.DataSource = query;
            //法三:
            var query = context.Info;
            dataGridView1.DataSource = query;
        }

        private void btn_ADD_Click(object sender, EventArgs e)
        {
            Info data = new Info();
            data.Code = txt_code.Text;
            data.Name = txt_name.Text;
            data.Nation = txt_nation.Text;
            data.Sex = Convert.ToBoolean(txt_sex.Text);
            data.Birthday = Convert.ToDateTime(txt_b.Text);

            context.Info.InsertOnSubmit(data);
            context.SubmitChanges();//提交
            FillInfo();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var query = from p in context.Info where p.Code == txt_code.Text select p;
            if (query.Count() > 0)
            {
                // query.Single();//第一条
                Info data = query.First();
                context.Info.DeleteOnSubmit(data);
                context.SubmitChanges();
            }
            FillInfo();

            //Form p in context.Info where
            //   Info data = context.Info.Where( => );
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var a = from p in context.Info where p.Code == txt_code.Text select p;
            if (a.Count() > 0)
            {
                Info data = a.First();
                data.Name = txt_name.Text;
                data.Sex = Convert.ToBoolean(txt_sex.Text);
                data.Nation = txt_nation.Text;
                data.Birthday = Convert.ToDateTime(txt_b.Text);
                context.SubmitChanges();
            }
            FillInfo();
        }

        private void btn_select_Click(object sender, EventArgs e)
        {

            #region meiyong
            //// e.Equals();
            //Type t = e.GetType();
            ////t.GetProperties();
            ////t.GetMethods();
            //Type s = sender.GetType();
            #endregion
            Button btn = (Button)sender;
            if (btn.Name == "btn_select")
            {
                if (tbx_code2.Text != "")
                {
                    //单条件等值查询
                    //var query = from p in context.Info where p.Code == tbx_code2.Text.Trim() select p;

                    var query = context.Info.Where(p => p.Code == tbx_code2.Text.Trim());//扩展方法 Lambda表达式
                    dataGridView1.DataSource = query;
                }
            }
            else if (btn.Name == "btn_select2")
            {
                if (tbx_code2.Text != "")
                {
                    //单条件不等值查询
                    //var query = from p in context.Info where p.Code != tbx_code2.Text.Trim() select p;
                    //>=  <=  同样可以用于筛选
                    var query = context.Info.Where(p => p.Code != tbx_code2.Text.Trim());
                    dataGridView1.DataSource = query;
                }
            }
            else if (btn.Name == "btn_duo")
            {
                //多条件查询
                var query = from p in context.Info where p.Sex == Convert.ToBoolean(cbx_sex.Text.Trim()) && p.Birthday.Value.Year > Convert.ToInt32(tbx_b_duo.Text.Trim()) select p;
                //或者
                //var query1 = context.Info.Where(p => p.Sex == Convert.ToBoolean(cbx_sex.Text.Trim()) && p.Birthday.Value.Year > Convert.ToInt32(tbx_b_duo.Text.Trim()));
                //var a=context.Info.Where (p=>p.Sex==Convert.ToBoolean(cbx_sex.Text.Trim())).Where(p=>p.Birthday.Value.Year> Convert.ToInt32(tbx_b_duo.Text.Trim()));//链式表达式 (&& 逻辑与可以用)
                dataGridView1.DataSource = query;
            }
            else if (btn.Name == "btn_select_mohu")
            {
                //var query = from p in context.Info where p.Name.Contains(tbx_xing.Text.Trim()) select p;//相当于like‘%某‘
                //var query = from p in context.Info where p.Name.StartsWith(tbx_xing.Text.Trim()) select p;//以什么开头
                //var query = from p in context.Info where p.Name.EndsWith(tbx_xing.Text.Trim()) select p;//以什么结尾
                //var query = from p in context.Info where p.Name.Substring(1, tbx_xing.TextLength) == tbx_xing.Text.Trim() select p;//截取第一位往后
                var query = context.Info.Where(p => p.Name.StartsWith(tbx_xing.Text.Trim()));

                dataGridView1.DataSource = query;
            }
            else if (btn.Name == "btn_shua")
            {
                FillInfo();
            }
            else if (btn.Name == "btn_jiao")
            {
                //交集相当于逻辑与 取公共部分
                var p1 = from p in context.Info where p.Sex == true select p;
                var p2 = context.Info.Where(p => p.Birthday.Value.Year > 1985);
                var query = p1.Intersect(p2);
                dataGridView1.DataSource = query;
            }
            else if (btn.Name == "btn_bing")
            {
                //并集相当于逻辑或
                var p1 = from p in context.Info where p.Sex == true select p;
                var p2 = context.Info.Where(p => p.Birthday.Value.Year > 1985);
                var query = p1.Union(p2);
                dataGridView1.DataSource = query;
            }
            else if (btn.Name == "btn_bu")
            {
                //差集 从一个集合减去另外一个集合 看谁减谁
                var p1 = from p in context.Info where p.Sex == true select p;
                var p2 = context.Info.Where(p => p.Birthday.Value.Year > 1985);
                var query = p1.Except(p2);
                dataGridView1.DataSource = query;
            }

        }

        private void btn_jige_Click(object sender, EventArgs e)
        {
           Button btn =(Button)sender;
           if (btn.Name=="btn_jige")
           {
               var query = context.Info.Where(p => p.Birthday.Value.Year > 1985);
               this.Text = query.Count().ToString();//个数
           }
           else if (btn.Name=="btn_sum")
           {
               var query = context.Info.Where(p => p.Birthday.Value.Year > 1985);
               this.Text = query.Sum(p=>DateTime.Now.Year-p.Birthday.Value.Year).ToString();//求和
           }
           else if (btn.Name == "btn_avg")
           {
               var query = context.Info.Where(p => p.Birthday.Value.Year > 1985);
               this.Text = query.Average(p => DateTime.Now.Year - p.Birthday.Value.Year).ToString();//求平均值
           }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            var query = context.Info.Where(p => p.Birthday.Value.Year > 1985);
            List<Info> list = query.ToList();//转集合
            dataGridView1.DataSource = list;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            var query = context.Info.Where(p => p.Birthday.Value.Year > 1985);
            Info[] list = query.ToArray();//转数组
            dataGridView1.DataSource = list;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            var query = context.Info.Where(p => p.Birthday.Value.Year > 1985);
            //Info data = query.Single();//单一
            Info data = query.First();
            dataGridView1.DataSource = data;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //每页多少条pagesize,要找第几页pageno
            var query=context.Info.Skip(1*1).Take(2);//skip跳过多少行,take取多少行
            dataGridView1.DataSource=query;
        }

    }
}

练习源码:http://pan.baidu.com/s/1c0wJ8i8

LinQ to sql 入门小教程:http://pan.baidu.com/s/1dD2NkcD

1.查询所有的

var query = from p in _Context.Info select p;
var query = _Context.Info;

2.单条件查询

等值查
var query = from p in _Context.Info where p.Code == "p002" select p;
注意:双等号,双引号。---C#语法。
var query = _Context.Info.Where(p => p.Code == "p002" );  //Lambda表达式
不等值查
            //var query = from p in _Context.Info where p.Code != "p002" select p;
            //var query = _Context.Info.Where(p => p.Code != "p002");  //Lambda表达式
            //var query = from p in _Context.Info where p.Birthday.Value.Year > 1985 select p;
            var query = _Context.Info.Where(p=>p.Birthday.Value.Year < 1985);

3.多条件查询

//var query = from p in _Context.Info where p.Sex == true && p.Birthday.Value.Year > 1985 select p;
            //var query = _Context.Info.Where(p=>p.Sex==true && p.Birthday.Value.Year>1985);
            var query = _Context.Info.Where(p => p.Sex == true).Where(p=>p.Birthday.Value.Year>1985) ; //多条件逻辑与可以用链式表达式写

4.模糊查询

//var query = from p in _Context.Info where p.Name.Contains("张") select p;  //相当于like ‘%张%‘
            //var query = from p in _Context.Info where p.Name.StartsWith("张") select p; // like ‘张%‘
            //var query = from p in _Context.Info where p.Name.EndsWith("张") select p;  //like ‘%张‘
            //var query = from p in _Context.Info where p.Name.Substring(1,1) == "张" select p;// like ‘_张%‘

var query = _Context.Info.Where(p => p.Name.StartsWith("张"));

5.集合操作

var q1 = from p in _Context.Info where p.Sex== true select p;
var q2 = _Context.Info.Where(p => p.Birthday.Value.Year > 1985);
           

var query = q1.Intersect(q2);

var query = q1.Union(q2);

var query = q2.Except(q1);

6.统计函数:

var query = _Context.Info.Where(p => p.Birthday.Value.Year > 1985);
            //this.Text = query.Count().ToString();
            //this.Text = query.Sum(p=>DateTime.Now.Year - p.Birthday.Value.Year).ToString();
            //this.Text = query.Average(p => DateTime.Now.Year - p.Birthday.Value.Year).ToString();
            //this.Text = query.Max(p => DateTime.Now.Year - p.Birthday.Value.Year).ToString();
            this.Text = query.Min(p => DateTime.Now.Year - p.Birthday.Value.Year).ToString();

7.转换操作

ToList(),ToArray(),First()/Single()

8.分页

var query = _Context.Info.Skip(2*2).Take(2);

时间: 2024-10-12 15:53:03

Linq To sql入门练习的相关文章

LINQ to SQL语句入门篇 纯属转载

Where操作 适用场景:实现过滤,查询等功能. 说明:与SQL命令中的Where作用相似,都是起到范围限定也就是过滤作用的,而判断条件就是它后面所接的子句. Where操作包括3种形式,分别为简单形式.关系条件形式.First()形式.下面分别用实例举例下: 1.简单形式: 例如:使用where筛选在伦敦的客户 var q = from c in db.Customers where c.City == "London" select c; 再如:筛选1994 年或之后雇用的雇员:

LINQ TO SQL Linq入门基础

我们以一个酒店管理系统的数据库为例子 表结构很简单:GuestInfo(客人信息表),Room(房间表),RoomType(房间类型表),HotelInfo(每个月盈利信息) 整体就是,Room中有个房间类型ID的外键,客人表中有个房间的ID的外键.月盈利信息先不管 准备:新建项目 linq_Ch4控制台程序,新建DB文件夹 右击DB文件夹,添加→新建项 选择LINQ to SQL类,文件名为 Hotel.dbml,添加 打开服务器资源管理器,我的快捷键是Ctrl+W+L 选中这四张表,往已经打

LinQ to Sql

在java平台上,ORM这一块Hiberante是相当的.但是在谈到.NET平台.ORM框架就有些不一样了.Nhibernate,Nbeat和Castel,以及我要说的linQ to Sql. Tosql是微软自己的产品.现在用的或许很少了,但是如果做一个中小型的项目,开发和部署还是很好的,不必考虑第 三方库.但是Tosql毕竟是直接面对数据库的.这个操作我有些用不惯,这里就简单介绍了. 要想使用Linq to Sql,实现需要建立好数据库. Step1 建立LINQ to SQL Classe

LINQ to SQL活学活用(1):这要打破旧观念

程序架构 现在比较经典的架构,看看下面图片. 如何实现 在一个N层应用程序中我们如何使用LINQ to SQL呢?这给刚刚入门的朋友的确是个难题,使用LINQ to SQL就是ORM技术,可以很轻松的实现对数据库记录增删查改操作,但是我们如何去"构建它"才更合理,更科学,更好用?这才是我们真正要学习的,使用面向对象的接口.抽象达到这个目的,面向接口编程就是更好的选择,可以更好的维护和测试. 下面一步一步完成这个程序吧,看到标题了吗?这篇是打破旧观念!看看接下来有什么神秘的地方.首先新建

linq to sql (Group By/Having/Count/Sum/Min/Max/Avg操作符) (转帖)

http://wenku.baidu.com/link?url=2RsCun4Mum1SLbh-LHYZpTmGFMiEukrWAoJGKGpkiHKHeafJcx2y-HVttNMb1BqJpNdwaOpCflaajFY6k36IoCH_D82bk2ccu468uzDRXvG 基于LINQ+to+Entity数据访问技术的应用研究 Group By/Having操作符 适用场景:分组数据,为我们查找数据缩小范围. 说明:分配并返回对传入参数进行分组操作后的可枚举对象.分组:延迟 1.简单形式:

LINQ To SQL 语法及实例大全

LINQ to SQL语句(1)之Where Where操作 适用场景:实现过滤,查询等功能. 说明:与SQL命令中的Where作用相似,都是起到范围限定也就是过滤作用的,而判断条件就是它后面所接的子句. Where操作包括3种形式,分别为简单形式.关系条件形式.First()形式.下面分别用实例举例下: 1.简单形式: 例如:使用where筛选在伦敦的客户 var q = from c in db.Customers where c.City == "London" select c

LINQ to SQL 中 Concat、Union、Intersect、Except 方法的使用

?  前言 LINQ to SQL 中需要对两个或多个数据集进行操作,比如:合并.取交集等,主要使用下面四个方法,这四个方法都是 System.Linq.IQueryable<out T> 接口的扩展方法,并且都是延迟加载方法,下面是使用的简单示例. ?  示例数据,数据表:Subject(科目表).Score(成绩表) 1.   Concat() 方法 1)   方法声明 public static IQueryable<TSource> Concat<TSource>

学习Linq To Sql

Linq To Sql 是一个非常神奇的东西 他可以让你把精力都放在业务逻辑上面,而用同一个语句操作多种关系型数据库 下面就让我们来看看他的用法.......... 数据库字段 use master go create database Learn_Linq_to_Sql go use Learn_Linq_to_Sql go create table Class ( CId int primary key identity(1,1), CName nvarchar(20) not null )

LINQ to SQL语句Concat/Union/Intersect/Except--2017年2月22日

Concat/Union/Intersect/Except操作 适用场景:对两个集合的处理,例如追加.合并.取相同项.相交项等等. Concat(连接) 说明:连接不同的集合,不会自动过滤相同项:延迟. 1.简单形式: var q = ( from c in db.Customers select c.Phone ).Concat( from c in db.Customers select c.Fax ).Concat( from e in db.Employees select e.Home