Linq To SQL笔记(一)
这几天刚学习了Linq,觉得非常好用,比起ADO.net来,写出来的代码非常简洁,也不易出错,很多工作都微软都给封装好了,我把这几天学习心得写出来给大家分享,请各位指点,我先写个例子。
我按这个例子的思路来写:
第一步应该定义数据库及数据表
有了Linq,我们可以非常简洁的创建一个数据库及数据表,并很好的与应用程序对象联系,先创建一个Person数据库映射类,这个类继承于DataContext,通过调用DataContext.CreateDatabase()就可以创建数据库,简单吧。
创建数据表,首先创建数据表映射类Student,在Person类中添加一个数据表对象即可,在创建数据库时就可以随数据库一起创建了,还可以通过扩展的CreateTable方法后期创建数据表。
第二步往数据表中添加数据
调用Table.InsertAllOnSubmit、Table.InsertlOnSubmit即可,通过DataContext.SubmitChanges把准备的数据更新到数据库内。与ADO.net不同,不再需要填写那个烦人的SQL语句insert,即简洁与不易出错,也少了数据类型转换,InsertAllOnSubmit参数只需要数据表映射类对象集合即可。
第三步修改、查询、删除数据
查询直接可以近似于SQL语句Linq语句,返回一个IEnumerable<Student>查询结果,可以对查询结果进行修改,通过Table.DeleteAllOnSubmit,
DataContext.SubmitChanges进行删除、修改操作。
利用linq,可以写出简洁、优雅的数据库操作程序。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data.Linq.Mapping;
6 using System.Data.Sql;
7 using System.Reflection;
8 #if DEBUG
9 using System.Diagnostics;
10 using NUnit.Framework;
11 #endif
12 namespace System.Data.Linq
13 {
14 public static class DataContextExtension//扩展DataContext,增加了几个方法
15 {
16 public static bool CreateTable(this DataContext context, Type type)
17 {//这个方法是转载别人的
18 MetaTable metaTable = context.Mapping.GetTable(type);
19 string typeName = "System.Data.Linq.SqlClient.SqlBuilder";
20 Type contextType = typeof(DataContext).Assembly.GetType(typeName);
21 if (contextType == null)
22 {
23 return false;
24 }
25 BindingFlags bf = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
26 object sql = contextType.InvokeMember("GetCreateTableCommand", bf, null, null, new[] { metaTable });
27 if (context.ExecuteCommand((string)sql, new object[] { }) <= 0)
28 {
29 return false;
30 }
31 return true;
32 }
33 public static bool CreateTable<TEntity>(this DataContext context)
34 {
35 return CreateTable(context, typeof(TEntity));
36 }
37 public static bool DeleteTable(this DataContext context, Type type)
38 {
39 MetaTable metaTable = context.Mapping.GetTable(type);
40 string cmdtext = "drop table "+metaTable.TableName;
41
42 if (context.ExecuteCommand(cmdtext, new object[] { }) > 0)
43 {
44 return true;
45 }
46 else
47 {
48 return false;
49 }
50 }
51
52 public static bool DeleteTable<TEntity>(this DataContext context)
53 {
54 return DeleteTable(context, typeof(TEntity));
55 }
56 }
57 #region 调试
58 #if DEBUG
59 [Table(Name = "Teacher")]
60 public class Teacher
61 {
62 [Column(IsPrimaryKey = true, CanBeNull = false)]
63 public int ID { get; set; }
64 [Column(CanBeNull = false)]
65 public string Name { get; set; }
66 [Column(CanBeNull = false)]
67 public int Age { get; set; }
68 }
69 [Table(Name = "Student")]
70 public class Student
71 {
72 [Column(CanBeNull = false, IsPrimaryKey = true)]
73 public int ID { get; set; }
74 [Column(CanBeNull = false)]
75 public string Name { get; set; }
76 [Column(CanBeNull = false)]
77 public int Age { get; set; }
78
79 public Student() { }
80
81 public Student(int id, string name, int age)
82 {
83 ID = id;
84 Name = name;
85 Age = age;
86 }
87
88 public override string ToString()
89 {
90 return ID.ToString() + "\t" + Name + "\t" + Age.ToString();
91 }
92 }
93 public class Person : DataContext
94 {
95 public Table<Student> Student;
96 public Person(string conString)
97 : base(conString)
98 {
99
100 }
101
102 }
103 [TestFixture]
104 public class LinqSql
105 {
106 public static string constr = AppDomain.CurrentDomain.BaseDirectory + @"\Person1.mdf";
107 public static Person db = new Person(constr);
108 [Test]
109 public static void CreateDatabase()
110 {
111 if (db.DatabaseExists())
112 {
113 db.DeleteDatabase();
114 }
115 db.CreateDatabase();
116 Trace.WriteLine(constr);
117 db.CreateTable(typeof(Teacher));
118 Table<Teacher> tl;
119 if ((tl =db.GetTable<Teacher>()) != null)
120 {
121 Trace.WriteLine(typeof(Teacher) + "表已经存在");
122 db.DeleteTable<Teacher>();
123 }
124 }
125
126 [Test]
127 public static void Insert()
128 {
129 List<Student> sl = new List<Student>();
130 sl.AddRange(new Student[] { new Student(1, "fds", 30),new Student(2, "gfdg", 22),
131 new Student(4, "fdsfds", 9),new Student(3, "fsde", 34)});
132
133 Table<Student> tl;
134 if ((tl = db.GetTable<Student>()) != null)
135 {
136 tl.InsertAllOnSubmit(sl);
137 db.SubmitChanges();
138 }
139 }
140 [Test]
141 public static void Delete()
142 {
143 Table<Student> tl;
144 if ((tl = db.GetTable<Student>()) != null)
145 {
146 IEnumerable<Student> q = from s in tl
147 where s.Age >= 30
148 select s;
149 tl.DeleteAllOnSubmit(q);
150 db.SubmitChanges();
151 }
152 }
153 [Test]
154 public static void Update()
155 {
156 Table<Student> tl;
157 if ((tl = db.GetTable<Student>()) != null)
158 {
159 IEnumerable<Student> q = from s in tl
160 where s.Age < 30
161 select s;
162
163 foreach (var item in q)
164 {
165 item.Age = 40;
166 }
167 db.SubmitChanges();
168 }
169 }
170
171 [Test]
172 public static void DeleteDatabase()
173 {
174 db.DeleteDatabase();
175 }
176 [Test]
177 public static void Select()
178 {
179 IEnumerable<Student> q = from rows in db.GetTable<Student>()
180 select rows;
181 foreach (var item in q)
182 {
183 Trace.WriteLine(item);
184 }
185 }
186 }
187 #endif
188 #endregion
189 }