In my first article, I am mainly using the Asp.net Mvc Framework + LinQ for development.
The following content involves the knowledge and generics of LinQ. If you have never understood it, search for related information in the blog garden. I will not introduce it here.
Assume that there is a user table in the database. (DEMO)
Create a LINQ to SQL class named testdata. dbml and drag the data table user. (Steps omitted)
Add a new class named tablemodel. The content is blank. Expand testdata. dbml, open the testdata. Designer. CS file, and add the inheritance tablemodel to the uesr class. (Why do you want to do this? I will explain it later)
Add updatecheck = updatecheck. Never for each field in the user class. Otherwise, the update will fail.
Add an interface named ibaserepository to act as an interface for all data table operation classes. The Code is as follows:
Code
1 public interface IBaseRepository <T> where T: TableModel
2 {
3 /// <summary>
4 // Add
5 /// </summary>
6 /// <param name = "obj"> </param>
7 void Insert (T obj );
8
9 /// <summary>
10 // modify
11 /// </summary>
12 /// <param name = "obj"> </param>
13 void Update (T obj );
14
15 /// <summary>
16 // Delete
17 /// </summary>
18 /// <param name = "obj"> </param>
19 void Delete (T obj );
20}
Where T: tablemodel. Some people may not know what it means... The generic T is limited to the tablemodel class, because the generic type must be a reference type when using the generic type of LINQ. Why should all the preceding user classes inherit tablemodel.
Add a new class that inherits the ibaserepository interface and implements the following three methods:
Code
1 public void Insert (T obj)
2 {
3 using (TestDataDataContext t = new TestDataDataContext ())
4 {
5 t. GetTable <T> (). InsertOnSubmit (obj );
6 t. SubmitChanges ();
7}
8}
9
10 public void Update (T obj)
11 {
12 using (TestDataDataContext t = new TestDataDataContext ())
13 {
14 t. GetTable <T> (). Attach (obj, true );
15 t. SubmitChanges ();
16}
17}
18
19 public void Delete (t obj)
20 {
21 using (testdatadatacontext T = new testdatadatacontext ())
22 {
23 T. gettable <t> (). Attach (OBJ, true );
24 T. gettable <t> (). deleteonsubmit (OBJ );
25 t. submitchanges ();
26}
27}
What is the meaning of the code? I will not explain it if I have learned about LINQ.
Create an interface named iuserrepository to operate on users and implement ibaserepository <user>
Create an implementation class userrepository to implement baserepository <user> and iuserrepository
Call:
IUserRepository userRe = new UserRepository ();
In this way, all operation classes of data tables can be added, deleted, and changed. You only need to implement the above interfaces and classes...
I am not very familiar with the design. Please give me more advice on errors...