comparison HowTo/Data/UpdateObject.cs @ 0:f990fcb411a9

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f990fcb411a9
1 using System;
2 using System.Collections.Generic;
3
4 using NUnit.Framework;
5
6 using BLToolkit.Data;
7 using BLToolkit.Mapping;
8 using BLToolkit.Reflection;
9
10 namespace HowTo.Data
11 {
12 [TestFixture]
13 public class UpdateObject
14 {
15 public enum Gender
16 {
17 [MapValue("F")] Female,
18 [MapValue("M")] Male,
19 [MapValue("U")] Unknown,
20 [MapValue("O")] Other
21 }
22
23 public abstract class Person
24 {
25 [MapField("PersonID")]
26 public abstract int ID { get; }
27
28 public abstract string LastName { get; set; }
29 public abstract string FirstName { get; set; }
30 public abstract string MiddleName { get; set; }
31 public abstract Gender Gender { get; set; }
32 }
33
34 int InsertPerson(Person person)
35 {
36 using (DbManager db = new DbManager())
37 {
38 return db
39 .SetCommand(@"
40 INSERT INTO Person
41 ( LastName, FirstName, MiddleName, Gender)
42 VALUES
43 (@LastName, @FirstName, @MiddleName, @Gender)
44
45 SELECT Cast(SCOPE_IDENTITY() as int)",
46 db.CreateParameters(person))
47 .ExecuteScalar<int>();
48 }
49 }
50
51 Person GetPersonByID(int id)
52 {
53 using (DbManager db = new DbManager())
54 {
55 return db
56 .SetCommand("SELECT * FROM Person WHERE PersonID = @id",
57 db.Parameter("@id", id))
58 .ExecuteObject<Person>();
59 }
60 }
61
62 void UpdatePerson(Person person)
63 {
64 using (DbManager db = new DbManager())
65 {
66 db
67 .SetCommand(@"
68 UPDATE
69 Person
70 SET
71 LastName = @LastName,
72 FirstName = @FirstName,
73 MiddleName = @MiddleName,
74 Gender = @Gender
75 WHERE
76 PersonID = @PersonID",
77 db.CreateParameters(person))
78 .ExecuteNonQuery();
79 }
80 }
81
82 void DeletePerson(int id)
83 {
84 using (DbManager db = new DbManager())
85 {
86 db
87 .SetCommand("DELETE FROM Person WHERE PersonID = @id",
88 db.Parameter("@id", id))
89 .ExecuteNonQuery();
90 }
91 }
92
93 [Test]
94 public void Test()
95 {
96 // Insert.
97 //
98 Person person = TypeAccessor<Person>.CreateInstanceEx();
99
100 person.FirstName = "Crazy";
101 person.LastName = "Frog";
102 person.Gender = Gender.Unknown;
103
104 int id = InsertPerson(person);
105
106 person = GetPersonByID(id);
107
108 TypeAccessor.WriteConsole(person);
109 Assert.IsNotNull(person);
110
111 // Update.
112 //
113 person.Gender = Gender.Other;
114
115 UpdatePerson(person);
116
117 person = GetPersonByID(id);
118
119 TypeAccessor.WriteConsole(person);
120 Assert.AreEqual(Gender.Other, person.Gender);
121
122 // Delete.
123 //
124 DeletePerson(id);
125
126 person = GetPersonByID(id);
127
128 Assert.IsNull(person);
129 }
130 }
131 }
132