comparison HowTo/Reflection/ObjectFactory.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.Reflection
11 {
12 [TestFixture]
13 public class ObjectFactoryTest
14 {
15 /*[a]*/[ObjectFactory(typeof(Person.ObjectFactory))]/*[/a]*/
16 public class Person
17 {
18 [MapField("PersonID")]
19 public int ID;
20
21 public string LastName;
22 public string FirstName;
23 public string MiddleName;
24
25 /*[a]*/class ObjectFactory : IObjectFactory/*[/a]*/
26 {
27 public object /*[a]*/CreateInstance(TypeAccessor typeAccessor, InitContext context)/*[/a]*/
28 {
29 // Get the object type indicator field.
30 //
31 object objectType = context.DataSource.GetValue(context.SourceObject, "PersonType");
32
33 // Target ObjectMapper must be changed in order to provide correct mapping.
34 //
35 switch ((string)objectType)
36 {
37 case "D": /*[a]*/context.ObjectMapper = ObjectMapper<Doctor>. Instance;/*[/a]*/ break;
38 case "P": /*[a]*/context.ObjectMapper = ObjectMapper<Patient>.Instance;/*[/a]*/ break;
39 }
40
41 // Create an object instance.
42 // Do not call ObjectMapper.CreateInstance as it will lead to infinite recursion.
43 //
44 return context.ObjectMapper./*[a]*/TypeAccessor/*[/a]*/.CreateInstance(context);
45 }
46 }
47 }
48
49 public class /*[a]*/Doctor : Person/*[/a]*/
50 {
51 public string Taxonomy;
52 }
53
54 public class /*[a]*/Patient : Person/*[/a]*/
55 {
56 public string Diagnosis;
57 }
58
59 [Test]
60 public void Test()
61 {
62 using (DbManager db = new DbManager())
63 {
64 List<Person> list = db
65 .SetCommand(@"
66 SELECT
67 ps.*,
68 d.Taxonomy,
69 p.Diagnosis,
70 CASE
71 WHEN d.PersonID IS NOT NULL THEN 'D'
72 WHEN p.PersonID IS NOT NULL THEN 'P'
73 END as PersonType
74 FROM
75 Person ps
76 LEFT JOIN Doctor d ON d.PersonID = ps.PersonID
77 LEFT JOIN Patient p ON p.PersonID = ps.PersonID
78 ORDER BY
79 ps.PersonID")
80 .ExecuteList<Person>();
81
82 Assert.AreEqual(list[0].GetType(), /*[a]*/typeof(Doctor)/*[/a]*/);
83 Assert.AreEqual(list[1].GetType(), /*[a]*/typeof(Patient)/*[/a]*/);
84
85 if (list.Count > 2)
86 Assert.AreEqual(list[2].GetType(), typeof(Person));
87 }
88 }
89 }
90 }