/PetaPoco.Tests/ColumnMapper.cs

http://github.com/toptensoftware/PetaPoco · C# · 90 lines · 71 code · 14 blank · 5 comment · 5 complexity · dae0cefdb209451326347759f547468d MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using PetaTest;
  6. namespace PetaPoco.Tests
  7. {
  8. public class Poco2
  9. {
  10. public string prop1 { get; set; }
  11. public string prop2 { get; set; }
  12. public string prop3 { get; set; }
  13. public string prop4 { get; set; }
  14. }
  15. public class MyColumnMapper : PetaPoco.IMapper
  16. {
  17. public void GetTableInfo(Type t, TableInfo ti)
  18. {
  19. if (t == typeof(Poco2))
  20. {
  21. ti.TableName = "petapoco";
  22. ti.PrimaryKey = "id";
  23. }
  24. }
  25. public bool MapPropertyToColumn(System.Reflection.PropertyInfo pi, ref string columnName, ref bool resultColumn)
  26. {
  27. if (pi.DeclaringType == typeof(Poco2))
  28. {
  29. switch (pi.Name)
  30. {
  31. case "prop1":
  32. // Leave this property as is
  33. return true;
  34. case "prop2":
  35. // Rename this column
  36. columnName = "remapped2";
  37. return true;
  38. case "prop3":
  39. // Mark this as a result column
  40. resultColumn = true;
  41. return true;
  42. case "prop4":
  43. // Ignore this property
  44. return false;
  45. }
  46. }
  47. // Do default property mapping
  48. return true;
  49. }
  50. public Func<object, object> GetFromDbConverter(System.Reflection.PropertyInfo pi, Type SourceType)
  51. {
  52. return null;
  53. }
  54. public Func<object, object> GetToDbConverter(Type SourceType)
  55. {
  56. return null;
  57. }
  58. }
  59. [TestFixture]
  60. public class ColumnMapper
  61. {
  62. [Test]
  63. public void NoColumnMapper()
  64. {
  65. PetaPoco.Database.Mapper = new MyColumnMapper();
  66. var pd=PetaPoco.Database.PocoData.ForType(typeof(Poco2));
  67. Assert.AreEqual(pd.Columns.Count, 3);
  68. Assert.AreEqual(pd.Columns["prop1"].PropertyInfo.Name, "prop1");
  69. Assert.AreEqual(pd.Columns["remapped2"].ColumnName, "remapped2");
  70. Assert.AreEqual(pd.Columns["prop3"].ColumnName, "prop3");
  71. Assert.AreEqual(string.Join(", ", pd.QueryColumns), "prop1, remapped2");
  72. Assert.AreEqual(pd.TableInfo.PrimaryKey, "id");
  73. Assert.AreEqual(pd.TableInfo.TableName, "petapoco");
  74. }
  75. }
  76. }