Inserts.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using System;
  2. using System.Linq;
  3. using PetaPoco.Core;
  4. using PetaPoco.Tests.Integration.Databases;
  5. using PetaPoco.Tests.Integration.Databases.MSSQL;
  6. using PetaPoco.Tests.Integration.Documentation.Pocos;
  7. using Shouldly;
  8. using Xunit;
  9. namespace PetaPoco.Tests.Integration.Documentation
  10. {
  11. [Collection("MssqlTests")]
  12. public class Inserts : BaseDatabase
  13. {
  14. public Inserts()
  15. : base(new MssqlDBTestProvider())
  16. {
  17. PocoData.FlushCaches();
  18. }
  19. [Fact]
  20. public void Insert()
  21. {
  22. // Create the person
  23. var person = new Person { Id = Guid.NewGuid(), Name = "PetaPoco", Dob = new DateTime(2011, 1, 1), Age = (DateTime.Now.Year - 2011), Height = 242 };
  24. // Tell PetaPoco to insert it
  25. var id = DB.Insert(person);
  26. // Obviously the ID returned will be the same at the one we set
  27. id.ShouldBe(person.Id);
  28. // Get a clone/copy from the DB
  29. var clone = DB.Single<Person>(id);
  30. // See, they're are the same
  31. clone.ShouldBe(person);
  32. // But, they're not not reference equals as PetaPoco doesn't cache because it's a MircoORM.
  33. person.Equals(clone).ShouldBeFalse();
  34. }
  35. [Fact]
  36. public void InsertAutoIncrement()
  37. {
  38. var person = new Person { Id = Guid.NewGuid(), Name = "PetaPoco", Dob = new DateTime(2011, 1, 1), Age = (DateTime.Now.Year - 2011), Height = 242 };
  39. DB.Insert(person);
  40. // Create the order
  41. var order = new Order
  42. {
  43. PersonId = person.Id,
  44. PoNumber = "PETAPOCO",
  45. Status = OrderStatus.Pending,
  46. CreatedBy = "Office PetaPoco",
  47. CreatedOn = new DateTime(1948, 1, 11, 4, 2, 4, DateTimeKind.Utc)
  48. };
  49. // Tell PetaPoco to insert it
  50. var id = DB.Insert(order);
  51. // PetaPoco updates the POCO's ID for us, see
  52. id.ShouldBe(order.Id);
  53. // Get a clone/copy from the DB
  54. var clone = DB.Single<Order>(id);
  55. // See, they're are the same
  56. clone.ShouldBe(order);
  57. // But, they're not not reference equals as PetaPoco doesn't cache because it's a MircoORM.
  58. order.Equals(clone).ShouldBeFalse();
  59. }
  60. [Fact]
  61. public void InsertToDifferentTable()
  62. {
  63. // Create the person
  64. var person = new Person { Id = Guid.NewGuid(), Name = "PetaPoco", Dob = new DateTime(2011, 1, 1), Age = (DateTime.Now.Year - 2011), Height = 242 };
  65. // Tell PetaPoco to insert it, but to the "SpecificPeople" table and not the "People" table.
  66. // Note: the id will only be returned if PetaPoco can tell which is the primary key via mapping or convention.
  67. var id = DB.Insert("SpecificPeople", person);
  68. // Obviously the ID returned will be the same at the one we set
  69. id.ShouldBe(person.Id);
  70. // Get a clone/copy from "People" table (Default table as per mappings)
  71. var clone = DB.SingleOrDefault<Person>(id);
  72. // As expected, doesn't exist
  73. clone.ShouldBeNull();
  74. // We need to get the clone/copy from the correct table
  75. // Note: we can't use auto select builder here because PetaPoco would create columns such as People.Id
  76. clone = DB.Query<Person>("SELECT * FROM [SpecificPeople] sp WHERE sp.[Id] = @0", id).Single();
  77. // See, they're are the same
  78. clone.ShouldBe(person);
  79. // But, they're not not reference equals as PetaPoco doesn't cache because it's a MircoORM.
  80. person.Equals(clone).ShouldBeFalse();
  81. }
  82. [Fact]
  83. public void InsertConventionalPoco()
  84. {
  85. // Clear out any notes and reset the ID sequence counter
  86. DB.Execute("TRUNCATE TABLE [Note]");
  87. // Insert some notes using all APIs
  88. // Each of the API usuages here are effectively the same, as PetaPoco is providing the correct unknown values.
  89. // This is because the poco has been mapped by convention and therefore PetaPoco understands how to do this.
  90. var id1 = DB.Insert(new Note { Text = "PetaPoco's note", CreatedOn = new DateTime(1948, 1, 11, 4, 2, 4, DateTimeKind.Utc) });
  91. var id2 = DB.Insert("Note", new Note { Text = "PetaPoco's note", CreatedOn = new DateTime(1948, 1, 11, 4, 2, 4, DateTimeKind.Utc) });
  92. var id3 = DB.Insert("Note", "Id", new Note { Text = "PetaPoco's note", CreatedOn = new DateTime(1948, 1, 11, 4, 2, 4, DateTimeKind.Utc) });
  93. var id4 = DB.Insert("Note", "Id", true, new Note { Text = "PetaPoco's note", CreatedOn = new DateTime(1948, 1, 11, 4, 2, 4, DateTimeKind.Utc) });
  94. // Am I right?
  95. id1.ShouldBe(1);
  96. id2.ShouldBe(2);
  97. id3.ShouldBe(3);
  98. id4.ShouldBe(4);
  99. // Just to be sure
  100. DB.ExecuteScalar<int>("SELECT COUNT(*) FROM [Note] WHERE CAST(Text AS NVARCHAR(MAX)) = @0", "PetaPoco's note").ShouldBe(4);
  101. }
  102. [Fact]
  103. public void InsertUnconventionalPoco()
  104. {
  105. // Create the UnconventionalPocos table
  106. DB.Execute(@"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES t WHERE t.TABLE_SCHEMA = 'dbo' AND t.TABLE_NAME = 'TBL_UnconventionalPocos')
  107. DROP TABLE dbo.[TBL_UnconventionalPocos]
  108. CREATE TABLE dbo.[TBL_UnconventionalPocos] (
  109. [PrimaryKey] INT IDENTITY(1,1) PRIMARY KEY,
  110. [Text] NTEXT NOT NULL
  111. )");
  112. // This POCO is unconventional because, when using the default conventional mapper, PetaPoco won't understand how this poco maps to the database.
  113. // To understand the power of unconventional mapping, a developer could configure it to work in this situation.
  114. var poco = new UnconventionalPoco { Text = "PetaPoco" };
  115. // Insert the poco
  116. var id = DB.Insert("TBL_UnconventionalPocos", "PrimaryKey", true, poco);
  117. // Get a clone/copy from the DB
  118. var clone = DB.Query<UnconventionalPoco>("SELECT * FROM [TBL_UnconventionalPocos] WHERE [PrimaryKey] = @0", id).Single();
  119. // See, they're are the same
  120. clone.ShouldBe(poco);
  121. // But, they're not not reference equals as PetaPoco doesn't cache because it's a MircoORM.
  122. poco.Equals(clone).ShouldBeFalse();
  123. }
  124. [Fact]
  125. public void InsertConventionalUnconventionalPoco()
  126. {
  127. // Create the UnconventionalPocos table
  128. DB.Execute(@"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES t WHERE t.TABLE_SCHEMA = 'dbo' AND t.TABLE_NAME = 'TBL_UnconventionalPocos')
  129. DROP TABLE dbo.[TBL_UnconventionalPocos]
  130. CREATE TABLE dbo.[TBL_UnconventionalPocos] (
  131. [PrimaryKey] INT IDENTITY(1,1) PRIMARY KEY,
  132. [Text] NTEXT NOT NULL
  133. )");
  134. // Reconfigure the convention mapper
  135. // Note: I can't think of a valid reason, other than for a purpose such as this, where you would configure the convention mapper in this way.
  136. ((ConventionMapper) DB.DefaultMapper).MapPrimaryKey = (ti, t) =>
  137. {
  138. var prop = t.GetProperties().FirstOrDefault(p => p.Name == "PrimaryKey");
  139. if (prop == null)
  140. return false;
  141. ti.PrimaryKey = prop.Name;
  142. ti.AutoIncrement = ((ConventionMapper) DB.DefaultMapper).IsPrimaryKeyAutoIncrement(prop.PropertyType);
  143. return true;
  144. };
  145. ((ConventionMapper) DB.DefaultMapper).InflectTableName = (i, tn) => "TBL_" + tn + "s";
  146. // Create the POCO
  147. var poco = new UnconventionalPoco { Text = "PetaPoco" };
  148. // Tell PetaPoco to insert it
  149. var id = DB.Insert(poco);
  150. // Get a clone/copy from the DB
  151. var clone = DB.SingleOrDefault<UnconventionalPoco>(id);
  152. // See, they're are the same
  153. clone.ShouldBe(poco);
  154. // But, they're not not reference equals as PetaPoco doesn't cache because it's a MircoORM.
  155. poco.Equals(clone).ShouldBeFalse();
  156. }
  157. [Fact]
  158. public void InsertAnonymousPocoWithConventionalNaming()
  159. {
  160. // Create the table for our unknown but conventional POCO
  161. DB.Execute(@"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES t WHERE t.TABLE_SCHEMA = 'dbo' AND t.TABLE_NAME = 'XFiles')
  162. DROP TABLE dbo.[XFiles]
  163. CREATE TABLE dbo.[XFiles] (
  164. [Id] INT IDENTITY(1,1) PRIMARY KEY,
  165. [FileName] VARCHAR(255) NOT NULL
  166. )");
  167. // Anonymous type are friend of PetaPoco
  168. var xfile = new { FileName = "Agent Mulder.sec" };
  169. // Tell PetaPoco to insert it
  170. var id = DB.Insert("XFiles", "Id", true, xfile);
  171. // Get a clone/copy from the DB
  172. // Note: Check out the name parameters - cool eh?
  173. var clone = DB.Query<dynamic>("SELECT * FROM [XFiles] WHERE [Id] = @Id", new { Id = id }).Single();
  174. // See, they're are the same
  175. id.ShouldBe((int) clone.Id);
  176. xfile.FileName.ShouldBe((string) clone.FileName);
  177. }
  178. [Fact]
  179. public void InsertDynamicUnknownPocoWithConventionalNaming()
  180. {
  181. // Create the table for our unknown but conventional POCO
  182. DB.Execute(@"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES t WHERE t.TABLE_SCHEMA = 'dbo' AND t.TABLE_NAME = 'XFiles')
  183. DROP TABLE dbo.[XFiles]
  184. CREATE TABLE dbo.[XFiles] (
  185. [Id] INT IDENTITY(1,1) PRIMARY KEY,
  186. [FileName] VARCHAR(255) NOT NULL
  187. )");
  188. // Dynamics type are friend of PetaPoco
  189. dynamic xfile = new System.Dynamic.ExpandoObject();
  190. xfile.FileName = "Agent Mulder.sec";
  191. // Tell PetaPoco to insert it
  192. var id = DB.Insert("XFiles", "Id", true, (object) xfile);
  193. // Get a clone/copy from the DB
  194. // Note: Check out the name parameters - cool eh?
  195. var clone = DB.Query<dynamic>("SELECT * FROM [XFiles] WHERE [Id] = @Id", new { Id = id }).Single();
  196. // See, they're are the same
  197. id.ShouldBe((int) clone.Id);
  198. ((string) xfile.FileName).ShouldBe((string) clone.FileName);
  199. }
  200. }
  201. }