VS2008开发-Linq to sql

首先创建一个C#控制台工程LINQToSQL,然后打开服务浏览器,单击右键,创建数据库Student

数据库创建数据库完成后,创建表stu_info 

在解决方案管理器中击右键,选择添加新项,在弹出窗口中选择Linq to sql class

创建完成后,在服务管理器中,拖到刚创建的表Stu_info到Student.dbml中,

打开Program.cs文件,键入如下代码:

  
    
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 namespace LINQToSQL
6 {
7 class Program
8 {
9 static void Main( string [] args)
10 {
11 // 插入测试
12 // Stu_Info s = new Stu_Info();
13 // s.Stu_Name = \"萧秋水\";
14 // s.Stu_Age = 20;
15 // StudentList.Insert_Student(s);
16 // Console.WriteLine(\"插入成功!\");
17
18 // 筛选测试
19
20 // IEnumerable students = StudentList.Select_Students();
21 // foreach (var stu in students)
22 // {
23 // Console.WriteLine(stu.Stu_Name);
24 // }
25
26 // 删除测试
27
28 // StudentList.Del_Students(1);
29
30 // 更新测试
31
32 /* Stu_Info s = new Stu_Info();
33 s.Stu_Name = \"燕狂徒\";
34 s.Stu_Age = 60;
35 StudentList.Update_Student(s);
36 */
37 }
38 }
39 public class StudentList
40 {
41 ///
42 /// 插入数据
43 ///
44 ///
45 ///
46 public static bool Insert_Student(Stu_Info stu)
47 {
48 StudentDataContext stu_DataContext = new StudentDataContext();
49 try
50 {
51 stu_DataContext.Stu_Infos.InsertOnSubmit(stu);
52
53 stu_DataContext.SubmitChanges();
54 return true ;
55 }
56 catch (Exception e)
57 {
58 Console.WriteLine(e);
59 return false ;
60 }
61 }
62 ///
63 /// 筛选数据
64 ///
65 ///
66 public static IEnumerable Select_Students()
67 {
68 StudentDataContext stu_DataContext = new StudentDataContext();
69 try
70 {
71 var s = from stu in stu_DataContext.Stu_Infos select stu;
72 return s;
73
74 // string sql = \"select * from Stu_Info\";
75 // Object[] obj = new Object { };
76 // stu_DataContext.Log = Console.Out;
77 // return stu_DataContext.ExecuteQuery(s.ToString(),obj);
78
79 }
80 catch (Exception e)
81 {
82 Console.WriteLine(e);
83 return null ;
84 }
85
86 }
87 ///
88 /// 删除数据
89 ///
90 ///
91 ///
92 public static bool Del_Students( int id)
93 {
94 StudentDataContext stu_DataContext = new StudentDataContext();
95 try
96 {
97 var s = from stu in stu_DataContext.Stu_Infos where stu.Stu_ID == 1 select stu;
98 if (s.Count() > 0 )
99 {
100 stu_DataContext.Stu_Infos.DeleteOnSubmit(s.First());
101 stu_DataContext.SubmitChanges();
102 }
103
104 return true ;
105
106 }
107 catch (Exception e)
108 {
109 Console.WriteLine(e);
110 return false ;
111 }
112
113 }
114 ///
115 /// 更新数据
116 ///
117 ///
118 ///
119 public static bool Update_Student(Stu_Info stu)
120 {
121 StudentDataContext stu_DataContext = new StudentDataContext();
122 try
123 {
124 var s = from student in stu_DataContext.Stu_Infos where student.Stu_ID == 2 select student;
125
126 foreach (Stu_Info newStu in s)
127 {
128 newStu.Stu_Name = stu.Stu_Name ;
129 newStu.Stu_Age = stu.Stu_Age;
130 }
131
132 stu_DataContext.SubmitChanges();
133
134 return true ;
135 }
136 catch (Exception e)
137 {
138 Console.WriteLine(e);
139 return false ;
140 }
141 }
142 }
143 }

你可能感兴趣的:(vs2008)