Tests.cs 108.1 KB
Newer Older
1
//#define POSTGRESQL // uncomment to run postgres tests
M
Marc Gravell 已提交
2

S
Sebastien Ros 已提交
3
#if DOTNET5_2
4 5 6 7 8
using IDbCommand = System.Data.Common.DbCommand;
using IDbDataParameter = System.Data.Common.DbParameter;
using IDbConnection = System.Data.Common.DbConnection;
using IDbTransaction = System.Data.Common.DbTransaction;
using IDataReader = System.Data.Common.DbDataReader;
M
Marc Gravell 已提交
9 10
#endif

11
using System;
S
Sam Saffron 已提交
12 13
using System.Collections.Generic;
using System.Data.SqlClient;
M
mgravell 已提交
14
using System.Linq;
15
using Dapper;
16
using System.IO;
S
Sam Saffron 已提交
17 18
using System.Data;
using System.Collections;
S
Sam Saffron 已提交
19
using System.Reflection;
20
using System.Dynamic;
21
using System.ComponentModel;
22
using Microsoft.CSharp.RuntimeBinder;
23 24
using System.Globalization;
using System.Threading;
25
using System.Data.SqlTypes;
26
using System.Diagnostics;
27
using Xunit;
M
Marc Gravell 已提交
28 29 30 31 32
#if EXTERNALS
using FirebirdSql.Data.FirebirdClient;
using System.Data.Entity.Spatial;
using Microsoft.SqlServer.Types;
using System.Data.SqlServerCe;
33 34 35
#if POSTGRESQL
using Npgsql;
#endif
M
Marc Gravell 已提交
36 37
#endif

S
Sebastien Ros 已提交
38
#if DOTNET5_2
M
Marc Gravell 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
namespace System.ComponentModel {
    public sealed class DescriptionAttribute : Attribute {
        public DescriptionAttribute(string description)
        {
            Description = description;
        }
        public string Description {get;private set;}
    }
}
namespace System
{   
    public enum GenericUriParserOptions
    {
        Default
    }
    public class GenericUriParser
    {
        private GenericUriParserOptions options;

        public GenericUriParser(GenericUriParserOptions options)
        {
            this.options = options;
        }
    }
}
#endif
S
Sam Saffron 已提交
65 66 67

namespace SqlMapper
{
68
    public partial class Tests : IDisposable
S
Sam Saffron 已提交
69
    {
N
Nick Craver 已提交
70
        readonly SqlConnection connection;
71

72
        public Tests()
73
        {
74
            connection = Program.GetOpenConnection();
V
vosen 已提交
75 76
        }

77
        public void Dispose()
V
vosen 已提交
78
        {
79
            connection?.Dispose();
V
vosen 已提交
80
        }
81

82 83
        // http://stackoverflow.com/q/8593871

84
        [Fact]
85 86 87
        public void TestListOfAnsiStrings()
        {
            var results = connection.Query<string>("select * from (select 'a' str union select 'b' union select 'c') X where str in @strings",
88 89 90 91
                new { strings = new[] {
                    new DbString { IsAnsi = true, Value = "a" },
                    new DbString { IsAnsi = true, Value = "b" }
                } }).ToList();
92

93 94
            results.Count.IsEqualTo(2);
            results.Sort();
95 96 97 98
            results[0].IsEqualTo("a");
            results[1].IsEqualTo("b");
        }

99
        [Fact]
S
Sam Saffron 已提交
100 101 102 103 104 105 106 107 108 109
        public void TestNullableGuidSupport()
        {
            var guid = connection.Query<Guid?>("select null").First();
            guid.IsNull();

            guid = Guid.NewGuid();
            var guid2 = connection.Query<Guid?>("select @guid", new { guid }).First();
            guid.IsEqualTo(guid2);
        }

110
        [Fact]
S
Sam Saffron 已提交
111 112 113 114 115 116 117
        public void TestNonNullableGuidSupport()
        {
            var guid = Guid.NewGuid();
            var guid2 = connection.Query<Guid?>("select @guid", new { guid }).First();
            Assert.IsTrue(guid == guid2);
        }

S
Sam Saffron 已提交
118 119 120 121 122 123 124
        struct Car
        {
            public enum TrapEnum : int
            {
                A = 1,
                B = 2
            }
125
#pragma warning disable 0649
S
Sam Saffron 已提交
126
            public string Name;
127
#pragma warning restore 0649
S
Sam Saffron 已提交
128 129
            public int Age { get; set; }
            public TrapEnum Trap { get; set; }
130

S
Sam Saffron 已提交
131 132
        }

133 134 135 136 137 138 139 140
        struct CarWithAllProps
        {
            public string Name { get; set; }
            public int Age { get; set; }

            public Car.TrapEnum Trap { get; set; }
        }

141
        [Fact]
S
Sam Saffron 已提交
142 143 144 145 146 147 148 149
        public void TestStructs()
        {
            var car = connection.Query<Car>("select 'Ford' Name, 21 Age, 2 Trap").First();

            car.Age.IsEqualTo(21);
            car.Name.IsEqualTo("Ford");
            ((int)car.Trap).IsEqualTo(2);
        }
150

151
        [Fact]
152 153 154 155 156 157 158 159 160 161
        public void TestStructAsParam()
        {
            var car1 = new CarWithAllProps { Name = "Ford", Age = 21, Trap = Car.TrapEnum.B };
            // note Car has Name as a field; parameters only respect properties at the moment
            var car2 = connection.Query<CarWithAllProps>("select @Name Name, @Age Age, @Trap Trap", car1).First();

            car2.Name.IsEqualTo(car1.Name);
            car2.Age.IsEqualTo(car1.Age);
            car2.Trap.IsEqualTo(car1.Trap);
        }
S
Sam Saffron 已提交
162

163
        [Fact]
S
Sam Saffron 已提交
164 165
        public void SelectListInt()
        {
166
            connection.Query<int>("select 1 union all select 2 union all select 3")
167
              .IsSequenceEqualTo(new[] { 1, 2, 3 });
S
Sam Saffron 已提交
168
        }
169 170

        [Fact]
M
mgravell 已提交
171 172
        public void SelectBinary()
        {
M
marc.gravell@gmail.com 已提交
173
            connection.Query<byte[]>("select cast(1 as varbinary(4))").First().SequenceEqual(new byte[] { 1 });
M
mgravell 已提交
174
        }
175 176

        [Fact]
S
Sam Saffron 已提交
177 178
        public void PassInIntArray()
        {
179
            connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[] { 1, 2, 3 }.AsEnumerable() })
180
             .IsSequenceEqualTo(new[] { 1, 2, 3 });
S
Sam Saffron 已提交
181
        }
S
Sam Saffron 已提交
182

183
        [Fact]
184 185 186 187 188 189
        public void PassInEmptyIntArray()
        {
            connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[0] })
             .IsSequenceEqualTo(new int[0]);
        }

190
        [Fact]
S
Sam Saffron 已提交
191 192 193
        public void TestSchemaChanged()
        {
            connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')");
194 195 196 197 198 199 200 201 202 203 204 205 206 207
            try
            {
                var d = connection.Query<Dog>("select * from #dog").Single();
                d.Name.IsEqualTo("Alf");
                d.Age.IsEqualTo(1);
                connection.Execute("alter table #dog drop column Name");
                d = connection.Query<Dog>("select * from #dog").Single();
                d.Name.IsNull();
                d.Age.IsEqualTo(1);
            }
            finally
            {
                connection.Execute("drop table #dog");
            }
S
Sam Saffron 已提交
208 209
        }

210
        [Fact]
S
Sam Saffron 已提交
211 212 213
        public void TestSchemaChangedMultiMap()
        {
            connection.Execute("create table #dog(Age int, Name nvarchar(max)) insert #dog values(1, 'Alf')");
214 215
            try
            {
N
Nigrimmist 已提交
216
                var tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", Tuple.Create, splitOn: "Age").Single();
S
Sam Saffron 已提交
217

218 219 220 221
                tuple.Item1.Name.IsEqualTo("Alf");
                tuple.Item1.Age.IsEqualTo(1);
                tuple.Item2.Name.IsEqualTo("Alf");
                tuple.Item2.Age.IsEqualTo(1);
S
Sam Saffron 已提交
222

223
                connection.Execute("alter table #dog drop column Name");
N
Nigrimmist 已提交
224
                tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", Tuple.Create, splitOn: "Age").Single();
M
marc.gravell@gmail.com 已提交
225

226 227 228 229 230 231 232 233 234
                tuple.Item1.Name.IsNull();
                tuple.Item1.Age.IsEqualTo(1);
                tuple.Item2.Name.IsNull();
                tuple.Item2.Age.IsEqualTo(1);
            }
            finally
            {
                connection.Execute("drop table #dog");
            }
S
Sam Saffron 已提交
235 236
        }

237
        [Fact]
238 239
        public void TestReadMultipleIntegersWithSplitOnAny()
        {
240
            connection.Query<int, int, int, Tuple<int, int, int>>(
241
                "select 1,2,3 union all select 4,5,6", Tuple.Create, splitOn: "*")
242
             .IsSequenceEqualTo(new[] { Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6) });
243
        }
S
Sam Saffron 已提交
244

245
        [Fact]
S
Sam Saffron 已提交
246 247
        public void TestDoubleParam()
        {
248
            connection.Query<double>("select @d", new { d = 0.1d }).First()
249
                .IsEqualTo(0.1d);
S
Sam Saffron 已提交
250 251
        }

252
        [Fact]
S
Sam Saffron 已提交
253 254
        public void TestBoolParam()
        {
255
            connection.Query<bool>("select @b", new { b = false }).First()
S
Sam Saffron 已提交
256
                .IsFalse();
S
Sam Saffron 已提交
257 258
        }

J
Jakub Konecki 已提交
259 260
        // http://code.google.com/p/dapper-dot-net/issues/detail?id=70
        // https://connect.microsoft.com/VisualStudio/feedback/details/381934/sqlparameter-dbtype-dbtype-time-sets-the-parameter-to-sqldbtype-datetime-instead-of-sqldbtype-time
261 262

        [Fact]
J
Jakub Konecki 已提交
263 264 265 266 267 268
        public void TestTimeSpanParam()
        {
            connection.Query<TimeSpan>("select @ts", new { ts = TimeSpan.FromMinutes(42) }).First()
                .IsEqualTo(TimeSpan.FromMinutes(42));
        }

269
        [Fact]
S
Sam Saffron 已提交
270 271
        public void TestStrings()
        {
272
            connection.Query<string>(@"select 'a' a union select 'b'")
273
                .IsSequenceEqualTo(new[] { "a", "b" });
S
Sam Saffron 已提交
274 275
        }

276
        // see http://stackoverflow.com/questions/16726709/string-format-with-sql-wildcard-causing-dapper-query-to-break
277
        [Fact]
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        public void CheckComplexConcat()
        {
            string end_wildcard = @"
SELECT * FROM #users16726709
WHERE (first_name LIKE CONCAT(@search_term, '%') OR last_name LIKE CONCAT(@search_term, '%'));";

            string both_wildcards = @"
SELECT * FROM #users16726709
WHERE (first_name LIKE CONCAT('%', @search_term, '%') OR last_name LIKE CONCAT('%', @search_term, '%'));";

            string formatted = @"
SELECT * FROM #users16726709
WHERE (first_name LIKE {0} OR last_name LIKE {0});";

            string use_end_only = @"CONCAT(@search_term, '%')";
            string use_both = @"CONCAT('%', @search_term, '%')";

            // if true, slower query due to not being able to use indices, but will allow searching inside strings 
            bool allow_start_wildcards = false;

            string query = String.Format(formatted, allow_start_wildcards ? use_both : use_end_only);
            string term = "F"; // the term the user searched for

            connection.Execute(@"create table #users16726709 (first_name varchar(200), last_name varchar(200))
302
insert #users16726709 values ('Fred','Bloggs') insert #users16726709 values ('Tony','Farcus') insert #users16726709 values ('Albert','TenoF')");
303 304 305 306 307 308 309 310

            // Using Dapper
            connection.Query(end_wildcard, new { search_term = term }).Count().IsEqualTo(2);
            connection.Query(both_wildcards, new { search_term = term }).Count().IsEqualTo(3);
            connection.Query(query, new { search_term = term }).Count().IsEqualTo(2);

        }

S
Sam Saffron 已提交
311 312 313 314 315 316 317 318 319 320
        public class Dog
        {
            public int? Age { get; set; }
            public Guid Id { get; set; }
            public string Name { get; set; }
            public float? Weight { get; set; }

            public int IgnoredProperty { get { return 1; } }
        }

321
        [Fact]
322 323 324
        public void TestExtraFields()
        {
            var guid = Guid.NewGuid();
325
            var dog = connection.Query<Dog>("select '' as Extra, 1 as Age, 0.1 as Name1 , Id = @id", new { id = guid });
326 327 328 329 330 331 332 333 334 335 336

            dog.Count()
               .IsEqualTo(1);

            dog.First().Age
                .IsEqualTo(1);

            dog.First().Id
                .IsEqualTo(guid);
        }

337
        [Fact]
338
        public void TestStrongType()
S
Sam Saffron 已提交
339
        {
340
            var guid = Guid.NewGuid();
341
            var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
342

S
Sam Saffron 已提交
343
            dog.Count()
344
                .IsEqualTo(1);
S
Sam Saffron 已提交
345 346 347

            dog.First().Age
                .IsNull();
348 349

            dog.First().Id
350
                .IsEqualTo(guid);
S
Sam Saffron 已提交
351 352
        }

353
        [Fact]
S
Sam Saffron 已提交
354 355
        public void TestSimpleNull()
        {
356
            connection.Query<DateTime?>("select null").First().IsNull();
S
Sam Saffron 已提交
357
        }
358

359
        [Fact]
S
Sam Saffron 已提交
360 361
        public void TestExpando()
        {
362
            var rows = connection.Query("select 1 A, 2 B union all select 3, 4").ToList();
363

S
Sam Saffron 已提交
364
            ((int)rows[0].A)
365
                .IsEqualTo(1);
S
Sam Saffron 已提交
366 367

            ((int)rows[0].B)
368
                .IsEqualTo(2);
S
Sam Saffron 已提交
369 370

            ((int)rows[1].A)
371
                .IsEqualTo(3);
S
Sam Saffron 已提交
372 373

            ((int)rows[1].B)
374
                .IsEqualTo(4);
S
Sam Saffron 已提交
375
        }
S
Sam Saffron 已提交
376

377
        [Fact]
S
Sam Saffron 已提交
378
        public void TestStringList()
S
Sam Saffron 已提交
379
        {
380 381
            connection.Query<string>("select * from (select 'a' as x union all select 'b' union all select 'c') as T where x in @strings", new { strings = new[] { "a", "b", "c" } })
                .IsSequenceEqualTo(new[] { "a", "b", "c" });
S
Sam Saffron 已提交
382

383 384
            connection.Query<string>("select * from (select 'a' as x union all select 'b' union all select 'c') as T where x in @strings", new { strings = new string[0] })
                   .IsSequenceEqualTo(new string[0]);
S
Sam Saffron 已提交
385 386
        }

387
        [Fact]
S
Sam Saffron 已提交
388 389
        public void TestExecuteCommand()
        {
390
            connection.Execute(@"
S
Sam Saffron 已提交
391 392 393 394 395 396
    set nocount on 
    create table #t(i int) 
    set nocount off 
    insert #t 
    select @a a union all select @b 
    set nocount on 
397
    drop table #t", new { a = 1, b = 2 }).IsEqualTo(2);
S
Sam Saffron 已提交
398
        }
399 400

        [Fact]
401 402 403
        public void TestExecuteCommandWithHybridParameters()
        {
            var p = new DynamicParameters(new { a = 1, b = 2 });
404
            p.Add("c", dbType: DbType.Int32, direction: ParameterDirection.Output);
405 406 407
            connection.Execute(@"set @c = @a + @b", p);
            p.Get<int>("@c").IsEqualTo(3);
        }
408 409

        [Fact]
410 411 412
        public void TestExecuteMultipleCommand()
        {
            connection.Execute("create table #t(i int)");
413 414 415 416 417 418 419 420 421 422 423
            try
            {
                int tally = connection.Execute(@"insert #t (i) values(@a)", new[] { new { a = 1 }, new { a = 2 }, new { a = 3 }, new { a = 4 } });
                int sum = connection.Query<int>("select sum(i) from #t").First();
                tally.IsEqualTo(4);
                sum.IsEqualTo(10);
            }
            finally
            {
                connection.Execute("drop table #t");
            }
424
        }
S
Sam Saffron 已提交
425

426 427
        class Student
        {
M
marc.gravell@gmail.com 已提交
428
            public string Name { get; set; }
429 430 431
            public int Age { get; set; }
        }

432
        [Fact]
433 434 435
        public void TestExecuteMultipleCommandStrongType()
        {
            connection.Execute("create table #t(Name nvarchar(max), Age int)");
436 437
            try
            {
438
                int tally = connection.Execute(@"insert #t (Name,Age) values(@Name, @Age)", new List<Student>
439 440 441 442
            {
                new Student{Age = 1, Name = "sam"},
                new Student{Age = 2, Name = "bob"}
            });
443 444 445 446 447 448 449 450
                int sum = connection.Query<int>("select sum(Age) from #t").First();
                tally.IsEqualTo(2);
                sum.IsEqualTo(3);
            }
            finally
            {
                connection.Execute("drop table #t");
            }
451 452
        }

453
        [Fact]
454 455 456 457 458 459 460 461 462
        public void TestExecuteMultipleCommandObjectArray()
        {
            connection.Execute("create table #t(i int)");
            int tally = connection.Execute(@"insert #t (i) values(@a)", new object[] { new { a = 1 }, new { a = 2 }, new { a = 3 }, new { a = 4 } });
            int sum = connection.Query<int>("select sum(i) from #t drop table #t").First();
            tally.IsEqualTo(4);
            sum.IsEqualTo(10);
        }

463
        [Fact]
S
Sam Saffron 已提交
464
        public void TestMassiveStrings()
465
        {
S
Sam Saffron 已提交
466
            var str = new string('X', 20000);
467
            connection.Query<string>("select @a", new { a = str }).First()
468
                .IsEqualTo(str);
S
Sam Saffron 已提交
469 470
        }

471 472 473 474 475 476
        class TestObj
        {
            public int _internal;
            internal int Internal { set { _internal = value; } }

            public int _priv;
S
Sam Saffron 已提交
477
            private int Priv { set { _priv = value; } }
M
Marc Gravell 已提交
478

479
            private int PrivGet { get { return _priv; } }
480 481
        }

482
        [Fact]
483 484
        public void TestSetInternal()
        {
485
            connection.Query<TestObj>("select 10 as [Internal]").First()._internal.IsEqualTo(10);
486 487
        }

488
        [Fact]
489 490
        public void TestSetPrivate()
        {
491
            connection.Query<TestObj>("select 10 as [Priv]").First()._priv.IsEqualTo(10);
492 493
        }

494
        [Fact]
M
Marc Gravell 已提交
495 496 497
        public void TestExpandWithNullableFields()
        {
            var row = connection.Query("select null A, 2 B").Single();
498

M
Marc Gravell 已提交
499 500 501 502 503 504
            ((int?)row.A)
                .IsNull();

            ((int?)row.B)
                .IsEqualTo(2);
        }
505

506
        [Fact]
507 508
        public void TestEnumeration()
        {
S
Sam Saffron 已提交
509 510 511 512
            var en = connection.Query<int>("select 1 as one union all select 2 as one", buffered: false);
            var i = en.GetEnumerator();
            i.MoveNext();

513 514 515
            bool gotException = false;
            try
            {
S
Sam Saffron 已提交
516
                var x = connection.Query<int>("select 1 as one", buffered: false).First();
517 518 519 520 521 522
            }
            catch (Exception)
            {
                gotException = true;
            }

S
Sam Saffron 已提交
523 524
            while (i.MoveNext())
            { }
525

526
            // should not exception, since enumerated
527
            en = connection.Query<int>("select 1 as one", buffered: false);
528 529 530 531

            gotException.IsTrue();
        }

532
        [Fact]
533 534
        public void TestEnumerationDynamic()
        {
S
Sam Saffron 已提交
535 536 537 538
            var en = connection.Query("select 1 as one union all select 2 as one", buffered: false);
            var i = en.GetEnumerator();
            i.MoveNext();

539 540 541
            bool gotException = false;
            try
            {
S
Sam Saffron 已提交
542
                var x = connection.Query("select 1 as one", buffered: false).First();
543 544 545 546 547 548
            }
            catch (Exception)
            {
                gotException = true;
            }

S
Sam Saffron 已提交
549 550
            while (i.MoveNext())
            { }
551 552

            // should not exception, since enumertated
S
Sam Saffron 已提交
553
            en = connection.Query("select 1 as one", buffered: false);
554 555 556

            gotException.IsTrue();
        }
557

558
        [Fact]
M
mgravell 已提交
559 560 561
        public void TestNakedBigInt()
        {
            long foo = 12345;
M
marc.gravell@gmail.com 已提交
562
            var result = connection.Query<long>("select @foo", new { foo }).Single();
M
mgravell 已提交
563 564 565
            foo.IsEqualTo(result);
        }

566
        [Fact]
M
mgravell 已提交
567 568 569 570 571 572
        public void TestBigIntMember()
        {
            long foo = 12345;
            var result = connection.Query<WithBigInt>(@"
declare @bar table(Value bigint)
insert @bar values (@foo)
M
marc.gravell@gmail.com 已提交
573
select * from @bar", new { foo }).Single();
M
mgravell 已提交
574 575
            result.Value.IsEqualTo(foo);
        }
576

M
mgravell 已提交
577 578 579 580
        class WithBigInt
        {
            public long Value { get; set; }
        }
S
Sam Saffron 已提交
581

582
        [Fact]
M
mgravell 已提交
583 584 585 586 587 588 589 590 591 592 593
        public void TestFieldsAndPrivates()
        {
            var data = connection.Query<TestFieldCaseAndPrivatesEntity>(
                @"select a=1,b=2,c=3,d=4,f='5'").Single();
            data.a.IsEqualTo(1);
            data.GetB().IsEqualTo(2);
            data.c.IsEqualTo(3);
            data.GetD().IsEqualTo(4);
            data.e.IsEqualTo(5);
        }

M
Marc Gravell 已提交
594
#if EXTERNALS
595
        [Fact]
596 597 598 599 600 601 602 603 604 605 606
        public void ExecuteReader()
        {
            var dt = new DataTable();
            dt.Load(connection.ExecuteReader("select 3 as [three], 4 as [four]"));
            dt.Columns.Count.IsEqualTo(2);
            dt.Columns[0].ColumnName.IsEqualTo("three");
            dt.Columns[1].ColumnName.IsEqualTo("four");
            dt.Rows.Count.IsEqualTo(1);
            ((int)dt.Rows[0][0]).IsEqualTo(3);
            ((int)dt.Rows[0][1]).IsEqualTo(4);
        }
M
Marc Gravell 已提交
607
#endif
M
mgravell 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        private class TestFieldCaseAndPrivatesEntity
        {
            public int a { get; set; }
            private int b { get; set; }
            public int GetB() { return b; }
            public int c = 0;
            private int d = 0;
            public int GetD() { return d; }
            public int e { get; set; }
            private string f
            {
                get { return e.ToString(); }
                set { e = int.Parse(value); }
            }
        }
M
mgravell 已提交
623

624 625 626 627 628 629 630 631 632 633 634 635
        class InheritanceTest1
        {
            public string Base1 { get; set; }
            public string Base2 { get; private set; }
        }

        class InheritanceTest2 : InheritanceTest1
        {
            public string Derived1 { get; set; }
            public string Derived2 { get; private set; }
        }

636
        [Fact]
637 638 639 640 641 642 643 644 645 646
        public void TestInheritance()
        {
            // Test that inheritance works.
            var list = connection.Query<InheritanceTest2>("select 'One' as Derived1, 'Two' as Derived2, 'Three' as Base1, 'Four' as Base2");
            list.First().Derived1.IsEqualTo("One");
            list.First().Derived2.IsEqualTo("Two");
            list.First().Base1.IsEqualTo("Three");
            list.First().Base2.IsEqualTo("Four");
        }

M
Marc Gravell 已提交
647
#if EXTERNALS
648
        [Fact]
649 650 651 652 653 654 655 656
        public void MultiRSSqlCE()
        {
            if (File.Exists("Test.sdf"))
                File.Delete("Test.sdf");

            var cnnStr = "Data Source = Test.sdf;";
            var engine = new SqlCeEngine(cnnStr);
            engine.CreateDatabase();
657

658 659 660 661 662 663 664 665 666 667 668
            using (var cnn = new SqlCeConnection(cnnStr))
            {
                cnn.Open();

                cnn.Execute("create table Posts (ID int, Title nvarchar(50), Body nvarchar(50), AuthorID int)");
                cnn.Execute("create table Authors (ID int, Name nvarchar(50))");

                cnn.Execute("insert Posts values (1,'title','body',1)");
                cnn.Execute("insert Posts values(2,'title2','body2',null)");
                cnn.Execute("insert Authors values(1,'sam')");

669
                var data = cnn.Query<PostCE, AuthorCE, PostCE>(@"select * from Posts p left join Authors a on a.ID = p.AuthorID", (post, author) => { post.Author = author; return post; }).ToList();
670
                var firstPost = data.First();
S
Sam Saffron 已提交
671 672 673
                firstPost.Title.IsEqualTo("title");
                firstPost.Author.Name.IsEqualTo("sam");
                data[1].Author.IsNull();
674 675 676
                cnn.Close();
            }
        }
677 678
        
        public class PostCE
679
        {
680 681 682 683 684
            public int ID { get; set; }
            public string Title { get; set; }
            public string Body { get; set; }

            public AuthorCE Author { get; set; }
S
Sam Saffron 已提交
685
        }
686 687

        public class AuthorCE
S
Sam Saffron 已提交
688
        {
689 690
            public int ID { get; set; }
            public string Name { get; set; }
691
        }
692
#endif
S
Sam Saffron 已提交
693

694
        [Fact]
S
Sam Saffron 已提交
695 696 697
        public void TestProcSupport()
        {
            var p = new DynamicParameters();
698 699 700
            p.Add("a", 11);
            p.Add("b", dbType: DbType.Int32, direction: ParameterDirection.Output);
            p.Add("c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
S
Sam Saffron 已提交
701 702 703 704 705 706 707 708 709 710 711 712

            connection.Execute(@"create proc #TestProc 
	@a int,
	@b int output
as 
begin
	set @b = 999
	select 1111
	return @a
end");
            connection.Query<int>("#TestProc", p, commandType: CommandType.StoredProcedure).First().IsEqualTo(1111);

713 714
            p.Get<int>("c").IsEqualTo(11);
            p.Get<int>("b").IsEqualTo(999);
S
Sam Saffron 已提交
715 716 717

        }

718
        [Fact]
M
mgravell 已提交
719 720 721 722
        public void TestDbString()
        {
            var obj = connection.Query("select datalength(@a) as a, datalength(@b) as b, datalength(@c) as c, datalength(@d) as d, datalength(@e) as e, datalength(@f) as f",
                new
M
Marc Gravell 已提交
723 724 725 726 727 728 729 730
                {
                    a = new DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi = true },
                    b = new DbString { Value = "abcde", IsFixedLength = true, Length = 10, IsAnsi = false },
                    c = new DbString { Value = "abcde", IsFixedLength = false, Length = 10, IsAnsi = true },
                    d = new DbString { Value = "abcde", IsFixedLength = false, Length = 10, IsAnsi = false },
                    e = new DbString { Value = "abcde", IsAnsi = true },
                    f = new DbString { Value = "abcde", IsAnsi = false },
                }).First();
M
mgravell 已提交
731 732 733 734 735 736 737 738
            ((int)obj.a).IsEqualTo(10);
            ((int)obj.b).IsEqualTo(20);
            ((int)obj.c).IsEqualTo(5);
            ((int)obj.d).IsEqualTo(10);
            ((int)obj.e).IsEqualTo(5);
            ((int)obj.f).IsEqualTo(10);
        }

739
        [Fact]
740 741
        public void TestDefaultDbStringDbType()
        {
742
            var origDefaultStringDbType = DbString.IsAnsiDefault;
743 744
            try
            {
745
                DbString.IsAnsiDefault = true;
746 747 748 749 750 751 752
                var a = new DbString { Value = "abcde" };
                var b = new DbString { Value = "abcde", IsAnsi = false };
                a.IsAnsi.IsTrue();
                b.IsAnsi.IsFalse();
            }
            finally
            {
753
                DbString.IsAnsiDefault = origDefaultStringDbType;
754 755 756
            }
        }

757
        [Fact]
758 759 760 761 762 763 764
        public void TestFastExpandoSupportsIDictionary()
        {
            var row = connection.Query("select 1 A, 'two' B").First() as IDictionary<string, object>;
            row["A"].IsEqualTo(1);
            row["B"].IsEqualTo("two");
        }

765 766 767 768 769
        [Fact]
        public void TestDapperSetsPrivates()
        {
            connection.Query<PrivateDan>("select 'one' ShadowInDB").First().Shadow.IsEqualTo(1);
        }
S
Sam Saffron 已提交
770 771 772 773

        class PrivateDan
        {
            public int Shadow { get; set; }
774 775 776
            private string ShadowInDB
            {
                set
S
Sam Saffron 已提交
777
                {
778
                    Shadow = value == "one" ? 1 : 0;
S
Sam Saffron 已提交
779 780 781
                }
            }
        }
M
mgravell 已提交
782

783

S
Sam Saffron 已提交
784 785
        /* TODO:
         * 
S
Sam Saffron 已提交
786 787 788 789 790 791 792 793
        public void TestMagicParam()
        {
            // magic params allow you to pass in single params without using an anon class
            // this test fails for now, but I would like to support a single param by parsing the sql with regex and remapping. 

            var first = connection.Query("select @a as a", 1).First();
            Assert.IsEqualTo(first.a, 1);
        }
S
Sam Saffron 已提交
794
         * */
S
Sam Saffron 已提交
795

796
        [Fact]
797 798 799
        public void TestUnexpectedDataMessage()
        {
            string msg = null;
M
marc.gravell@gmail.com 已提交
800 801
            try
            {
802 803
                connection.Query<int>("select count(1) where 1 = @Foo", new WithBizarreData { Foo = new GenericUriParser(GenericUriParserOptions.Default), Bar = 23 }).First();

M
marc.gravell@gmail.com 已提交
804 805
            }
            catch (Exception ex)
806 807 808 809 810
            {
                msg = ex.Message;
            }
            msg.IsEqualTo("The member Foo of type System.GenericUriParser cannot be used as a parameter value");
        }
M
Marc Gravell 已提交
811

812
        [Fact]
813 814 815 816 817 818
        public void TestUnexpectedButFilteredDataMessage()
        {
            int i = connection.Query<int>("select @Bar", new WithBizarreData { Foo = new GenericUriParser(GenericUriParserOptions.Default), Bar = 23 }).Single();

            i.IsEqualTo(23);
        }
M
mgravell 已提交
819

820 821 822 823 824 825
        class WithBizarreData
        {
            public GenericUriParser Foo { get; set; }
            public int Bar { get; set; }
        }

M
mgravell 已提交
826 827 828 829 830
        class WithCharValue
        {
            public char Value { get; set; }
            public char? ValueNullable { get; set; }
        }
831 832

        [Fact]
M
mgravell 已提交
833 834 835 836 837 838 839 840 841 842 843
        public void TestCharInputAndOutput()
        {
            const char test = '〠';
            char c = connection.Query<char>("select @c", new { c = test }).Single();

            c.IsEqualTo(test);

            var obj = connection.Query<WithCharValue>("select @Value as Value", new WithCharValue { Value = c }).Single();

            obj.Value.IsEqualTo(test);
        }
844 845

        [Fact]
M
mgravell 已提交
846 847 848 849 850 851 852 853 854 855 856
        public void TestNullableCharInputAndOutputNonNull()
        {
            char? test = '〠';
            char? c = connection.Query<char?>("select @c", new { c = test }).Single();

            c.IsEqualTo(test);

            var obj = connection.Query<WithCharValue>("select @ValueNullable as ValueNullable", new WithCharValue { ValueNullable = c }).Single();

            obj.ValueNullable.IsEqualTo(test);
        }
857 858

        [Fact]
M
mgravell 已提交
859 860 861 862 863 864 865 866 867 868 869
        public void TestNullableCharInputAndOutputNull()
        {
            char? test = null;
            char? c = connection.Query<char?>("select @c", new { c = test }).Single();

            c.IsEqualTo(test);

            var obj = connection.Query<WithCharValue>("select @ValueNullable as ValueNullable", new WithCharValue { ValueNullable = c }).Single();

            obj.ValueNullable.IsEqualTo(test);
        }
870 871

        [Fact]
872 873 874 875 876 877 878
        public void TestInvalidSplitCausesNiceError()
        {
            try
            {
                connection.Query<User, User, User>("select 1 A, 2 B, 3 C", (x, y) => x);
            }
            catch (ArgumentException)
M
marc.gravell@gmail.com 已提交
879
            {
880 881 882 883 884 885 886 887 888 889 890 891
                // expecting an app exception due to multi mapping being bodged 
            }

            try
            {
                connection.Query<dynamic, dynamic, dynamic>("select 1 A, 2 B, 3 C", (x, y) => x);
            }
            catch (ArgumentException)
            {
                // expecting an app exception due to multi mapping being bodged 
            }
        }
892

893
        [Fact]
894 895 896 897 898 899 900 901 902 903 904 905
        public void TestCustomParameters()
        {
            var args = new DbParams {
                new SqlParameter("foo", 123),
                new SqlParameter("bar", "abc")
            };
            var result = connection.Query("select Foo=@foo, Bar=@bar", args).Single();
            int foo = result.Foo;
            string bar = result.Bar;
            foo.IsEqualTo(123);
            bar.IsEqualTo("abc");
        }
906 907
        
        [Fact]
908 909 910 911 912
        public void TestDynamicParamNullSupport()
        {
            var p = new DynamicParameters();

            p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
M
marc.gravell@gmail.com 已提交
913
            connection.Execute("select @b = null", p);
914 915 916

            p.Get<int?>("@b").IsNull();
        }
917

M
Marc Gravell 已提交
918 919

#if EXTERNALS
920
        [Fact]
M
mgravell 已提交
921
        public void TestLinqBinaryToClass()
922
        {
M
mgravell 已提交
923 924
            byte[] orig = new byte[20];
            new Random(123456).NextBytes(orig);
M
mgravell 已提交
925 926 927 928 929
            var input = new System.Data.Linq.Binary(orig);

            var output = connection.Query<WithBinary>("select @input as [Value]", new { input }).First().Value;

            output.ToArray().IsSequenceEqualTo(orig);
930
        }
931 932
        
        [Fact]
M
mgravell 已提交
933
        public void TestLinqBinaryRaw()
934
        {
M
mgravell 已提交
935 936
            byte[] orig = new byte[20];
            new Random(123456).NextBytes(orig);
M
mgravell 已提交
937 938 939 940 941
            var input = new System.Data.Linq.Binary(orig);

            var output = connection.Query<System.Data.Linq.Binary>("select @input as [Value]", new { input }).First();

            output.ToArray().IsSequenceEqualTo(orig);
942 943
        }

M
mgravell 已提交
944
        class WithBinary
945
        {
M
mgravell 已提交
946
            public System.Data.Linq.Binary Value { get; set; }
947
        }
M
Marc Gravell 已提交
948
#endif
949 950 951 952 953 954

        class WithPrivateConstructor
        {
            public int Foo { get; set; }
            private WithPrivateConstructor() { }
        }
955 956 957

        [Fact]
        public void TestWithNonPublicConstructor()
M
marc.gravell@gmail.com 已提交
958
        {
959 960
            var output = connection.Query<WithPrivateConstructor>("select 1 as Foo").First();
            output.Foo.IsEqualTo(1);
M
marc.gravell@gmail.com 已提交
961
        }
962 963


964
        [Fact]
965
        public void WorkDespiteHavingWrongStructColumnTypes()
966
        {
967 968
            var hazInt = connection.Query<CanHazInt>("select cast(1 as bigint) Value").Single();
            hazInt.Value.Equals(1);
969
        }
970

971
        [Fact]
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
        public void TestProcWithOutParameter()
        {
            connection.Execute(
                @"CREATE PROCEDURE #TestProcWithOutParameter
        @ID int output,
        @Foo varchar(100),
        @Bar int
        AS
        SET @ID = @Bar + LEN(@Foo)");
            var obj = new
            {
                ID = 0,
                Foo = "abc",
                Bar = 4
            };
            var args = new DynamicParameters(obj);
            args.Add("ID", 0, direction: ParameterDirection.Output);
            connection.Execute("#TestProcWithOutParameter", args, commandType: CommandType.StoredProcedure);
            args.Get<int>("ID").IsEqualTo(7);
        }
992 993

        [Fact]
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        public void TestProcWithOutAndReturnParameter()
        {
            connection.Execute(
                @"CREATE PROCEDURE #TestProcWithOutAndReturnParameter
        @ID int output,
        @Foo varchar(100),
        @Bar int
        AS
        SET @ID = @Bar + LEN(@Foo)
        RETURN 42");
            var obj = new
            {
                ID = 0,
                Foo = "abc",
                Bar = 4
            };
            var args = new DynamicParameters(obj);
            args.Add("ID", 0, direction: ParameterDirection.Output);
            args.Add("result", 0, direction: ParameterDirection.ReturnValue);
            connection.Execute("#TestProcWithOutAndReturnParameter", args, commandType: CommandType.StoredProcedure);
            args.Get<int>("ID").IsEqualTo(7);
            args.Get<int>("result").IsEqualTo(42);
        }
1017 1018 1019 1020
        struct CanHazInt
        {
            public int Value { get; set; }
        }
1021 1022

        [Fact]
M
mgravell 已提交
1023 1024 1025 1026 1027 1028
        public void TestInt16Usage()
        {
            connection.Query<short>("select cast(42 as smallint)").Single().IsEqualTo((short)42);
            connection.Query<short?>("select cast(42 as smallint)").Single().IsEqualTo((short?)42);
            connection.Query<short?>("select cast(null as smallint)").Single().IsEqualTo((short?)null);

1029 1030 1031
            connection.Query<ShortEnum>("select cast(42 as smallint)").Single().IsEqualTo((ShortEnum)42);
            connection.Query<ShortEnum?>("select cast(42 as smallint)").Single().IsEqualTo((ShortEnum?)42);
            connection.Query<ShortEnum?>("select cast(null as smallint)").Single().IsEqualTo((ShortEnum?)null);
M
mgravell 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

            var row =
                connection.Query<WithInt16Values>(
                    "select cast(1 as smallint) as NonNullableInt16, cast(2 as smallint) as NullableInt16, cast(3 as smallint) as NonNullableInt16Enum, cast(4 as smallint) as NullableInt16Enum")
                    .Single();
            row.NonNullableInt16.IsEqualTo((short)1);
            row.NullableInt16.IsEqualTo((short)2);
            row.NonNullableInt16Enum.IsEqualTo(ShortEnum.Three);
            row.NullableInt16Enum.IsEqualTo(ShortEnum.Four);

            row =
    connection.Query<WithInt16Values>(
        "select cast(5 as smallint) as NonNullableInt16, cast(null as smallint) as NullableInt16, cast(6 as smallint) as NonNullableInt16Enum, cast(null as smallint) as NullableInt16Enum")
        .Single();
            row.NonNullableInt16.IsEqualTo((short)5);
            row.NullableInt16.IsEqualTo((short?)null);
            row.NonNullableInt16Enum.IsEqualTo(ShortEnum.Six);
            row.NullableInt16Enum.IsEqualTo((ShortEnum?)null);
        }
1051 1052

        [Fact]
1053 1054 1055 1056 1057 1058 1059 1060 1061
        public void TestInt32Usage()
        {
            connection.Query<int>("select cast(42 as int)").Single().IsEqualTo((int)42);
            connection.Query<int?>("select cast(42 as int)").Single().IsEqualTo((int?)42);
            connection.Query<int?>("select cast(null as int)").Single().IsEqualTo((int?)null);

            connection.Query<IntEnum>("select cast(42 as int)").Single().IsEqualTo((IntEnum)42);
            connection.Query<IntEnum?>("select cast(42 as int)").Single().IsEqualTo((IntEnum?)42);
            connection.Query<IntEnum?>("select cast(null as int)").Single().IsEqualTo((IntEnum?)null);
M
mgravell 已提交
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
            var row =
                connection.Query<WithInt32Values>(
                    "select cast(1 as int) as NonNullableInt32, cast(2 as int) as NullableInt32, cast(3 as int) as NonNullableInt32Enum, cast(4 as int) as NullableInt32Enum")
                    .Single();
            row.NonNullableInt32.IsEqualTo((int)1);
            row.NullableInt32.IsEqualTo((int)2);
            row.NonNullableInt32Enum.IsEqualTo(IntEnum.Three);
            row.NullableInt32Enum.IsEqualTo(IntEnum.Four);

            row =
    connection.Query<WithInt32Values>(
        "select cast(5 as int) as NonNullableInt32, cast(null as int) as NullableInt32, cast(6 as int) as NonNullableInt32Enum, cast(null as int) as NullableInt32Enum")
        .Single();
            row.NonNullableInt32.IsEqualTo((int)5);
            row.NullableInt32.IsEqualTo((int?)null);
            row.NonNullableInt32Enum.IsEqualTo(IntEnum.Six);
            row.NullableInt32Enum.IsEqualTo((IntEnum?)null);
        }
M
mgravell 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091

        public class WithInt16Values
        {
            public short NonNullableInt16 { get; set; }
            public short? NullableInt16 { get; set; }
            public ShortEnum NonNullableInt16Enum { get; set; }
            public ShortEnum? NullableInt16Enum { get; set; }
        }
        public enum ShortEnum : short
        {
            Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
        }
        public class WithInt32Values
        {
            public int NonNullableInt32 { get; set; }
            public int? NullableInt32 { get; set; }
            public IntEnum NonNullableInt32Enum { get; set; }
            public IntEnum? NullableInt32Enum { get; set; }
        }
        public enum IntEnum : int
        {
            Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6
M
mgravell 已提交
1103
        }
1104

1105
        [Fact]
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
        public void TestTransactionCommit()
        {
            try
            {
                connection.Execute("create table #TransactionTest ([ID] int, [Value] varchar(32));");

                using (var transaction = connection.BeginTransaction())
                {
                    connection.Execute("insert into #TransactionTest ([ID], [Value]) values (1, 'ABC');", transaction: transaction);

                    transaction.Commit();
                }

                connection.Query<int>("select count(*) from #TransactionTest;").Single().IsEqualTo(1);
            }
            finally
            {
                connection.Execute("drop table #TransactionTest;");
            }
        }

1127
        [Fact]
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        public void TestTransactionRollback()
        {
            connection.Execute("create table #TransactionTest ([ID] int, [Value] varchar(32));");

            try
            {
                using (var transaction = connection.BeginTransaction())
                {
                    connection.Execute("insert into #TransactionTest ([ID], [Value]) values (1, 'ABC');", transaction: transaction);

                    transaction.Rollback();
                }

                connection.Query<int>("select count(*) from #TransactionTest;").Single().IsEqualTo(0);
            }
            finally
            {
                connection.Execute("drop table #TransactionTest;");
            }
        }

1149
        [Fact]
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        public void TestCommandWithInheritedTransaction()
        {
            connection.Execute("create table #TransactionTest ([ID] int, [Value] varchar(32));");

            try
            {
                using (var transaction = connection.BeginTransaction())
                {
                    var transactedConnection = new TransactedConnection(connection, transaction);

                    transactedConnection.Execute("insert into #TransactionTest ([ID], [Value]) values (1, 'ABC');");

                    transaction.Rollback();
                }

                connection.Query<int>("select count(*) from #TransactionTest;").Single().IsEqualTo(0);
            }
            finally
            {
                connection.Execute("drop table #TransactionTest;");
            }
        }

1173
        [Fact]
1174 1175 1176 1177
        public void TestReaderWhenResultsChange()
        {
            try
            {
1178

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                connection.Execute("create table #ResultsChange (X int);create table #ResultsChange2 (Y int);insert #ResultsChange (X) values(1);insert #ResultsChange2 (Y) values(1);");

                var obj1 = connection.Query<ResultsChangeType>("select * from #ResultsChange").Single();
                obj1.X.IsEqualTo(1);
                obj1.Y.IsEqualTo(0);
                obj1.Z.IsEqualTo(0);

                var obj2 = connection.Query<ResultsChangeType>("select * from #ResultsChange rc inner join #ResultsChange2 rc2 on rc2.Y=rc.X").Single();
                obj2.X.IsEqualTo(1);
                obj2.Y.IsEqualTo(1);
                obj2.Z.IsEqualTo(0);

                connection.Execute("alter table #ResultsChange add Z int null");
                connection.Execute("update #ResultsChange set Z = 2");

                var obj3 = connection.Query<ResultsChangeType>("select * from #ResultsChange").Single();
                obj3.X.IsEqualTo(1);
                obj3.Y.IsEqualTo(0);
                obj3.Z.IsEqualTo(2);

                var obj4 = connection.Query<ResultsChangeType>("select * from #ResultsChange rc inner join #ResultsChange2 rc2 on rc2.Y=rc.X").Single();
                obj4.X.IsEqualTo(1);
                obj4.Y.IsEqualTo(1);
                obj4.Z.IsEqualTo(2);
1203 1204
            }
            finally
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
            {
                connection.Execute("drop table #ResultsChange;drop table #ResultsChange2;");
            }
        }
        class ResultsChangeType
        {
            public int X { get; set; }
            public int Y { get; set; }
            public int Z { get; set; }
        }

1216
        [Fact]
1217 1218 1219 1220 1221 1222 1223 1224
        public void TestCustomTypeMap()
        {
            // default mapping
            var item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
            item.A.IsEqualTo("AVal");
            item.B.IsEqualTo("BVal");

            // custom mapping
1225
            var map = new CustomPropertyTypeMap(typeof(TypeWithMapping),
N
Nigrimmist 已提交
1226
                (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
            Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);

            item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
            item.A.IsEqualTo("BVal");
            item.B.IsEqualTo("AVal");

            // reset to default
            Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), null);
            item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
            item.A.IsEqualTo("AVal");
            item.B.IsEqualTo("BVal");
        }
M
Marc Gravell 已提交
1239 1240 1241
        static string GetDescriptionFromAttribute(MemberInfo member)
        {
            if (member == null) return null;
S
Sebastien Ros 已提交
1242
#if DOTNET5_2
M
Marc Gravell 已提交
1243
            var data = member.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(DescriptionAttribute));
N
Nick Craver 已提交
1244
            return (string) data?.ConstructorArguments.Single().Value;
M
Marc Gravell 已提交
1245 1246 1247 1248 1249
#else
            var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
            return attrib == null ? null : attrib.Description;
#endif
        }
1250 1251 1252 1253 1254 1255 1256 1257 1258
        public class TypeWithMapping
        {
            [Description("B")]
            public string A { get; set; }

            [Description("A")]
            public string B { get; set; }
        }

1259 1260 1261 1262 1263 1264 1265
        public class WrongTypes
        {
            public int A { get; set; }
            public double B { get; set; }
            public long C { get; set; }
            public bool D { get; set; }
        }
1266

1267
        [Fact]
1268 1269 1270 1271 1272 1273 1274 1275
        public void TestWrongTypes_WithRightTypes()
        {
            var item = connection.Query<WrongTypes>("select 1 as A, cast(2.0 as float) as B, cast(3 as bigint) as C, cast(1 as bit) as D").Single();
            item.A.Equals(1);
            item.B.Equals(2.0);
            item.C.Equals(3L);
            item.D.Equals(true);
        }
1276

1277
        [Fact]
1278 1279 1280 1281 1282 1283 1284 1285 1286
        public void TestWrongTypes_WithWrongTypes()
        {
            var item = connection.Query<WrongTypes>("select cast(1.0 as float) as A, 2 as B, 3 as C, cast(1 as bigint) as D").Single();
            item.A.Equals(1);
            item.B.Equals(2.0);
            item.C.Equals(3L);
            item.D.Equals(true);
        }

1287

1288
        [Fact]
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        public void Issue_40_AutomaticBoolConversion()
        {
            var user = connection.Query<Issue40_User>("select UserId=1,Email='abc',Password='changeme',Active=cast(1 as tinyint)").Single();
            user.Active.IsTrue();
            user.UserID.IsEqualTo(1);
            user.Email.IsEqualTo("abc");
            user.Password.IsEqualTo("changeme");
        }

        public class Issue40_User
        {
1300 1301
            public Issue40_User()
            {
1302
                Email = Password = string.Empty;
1303 1304 1305 1306 1307
            }
            public int UserID { get; set; }
            public string Email { get; set; }
            public string Password { get; set; }
            public bool Active { get; set; }
1308 1309
        }

1310 1311 1312 1313 1314 1315
        SqlConnection GetClosedConnection()
        {
            var conn = new SqlConnection(connection.ConnectionString);
            if (conn.State != ConnectionState.Closed) throw new InvalidOperationException("should be closed!");
            return conn;
        }
1316 1317

        [Fact]
1318 1319 1320 1321 1322 1323 1324 1325
        public void ExecuteFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                conn.Execute("-- nop");
                conn.State.IsEqualTo(ConnectionState.Closed);
            }
        }
1326 1327 1328 1329 1330 1331 1332 1333
        class Multi1
        {
            public int Id { get; set; }
        }
        class Multi2
        {
            public int Id { get; set; }
        }
1334 1335

        [Fact]
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
        public void QueryMultimapFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                conn.State.IsEqualTo(ConnectionState.Closed);
                var i = conn.Query<Multi1, Multi2, int>("select 2 as [Id], 3 as [Id]", (x, y) => x.Id + y.Id).Single();
                conn.State.IsEqualTo(ConnectionState.Closed);
                i.IsEqualTo(5);
            }
        }
1346 1347

        [Fact]
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
        public void QueryMultiple2FromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                conn.State.IsEqualTo(ConnectionState.Closed);
                using (var multi = conn.QueryMultiple("select 1 select 2 select 3"))
                {
                    multi.Read<int>().Single().IsEqualTo(1);
                    multi.Read<int>().Single().IsEqualTo(2);
                    // not reading 3 is intentional here
                }
                conn.State.IsEqualTo(ConnectionState.Closed);
            }
        }
1362 1363

        [Fact]
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        public void ExecuteInvalidFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                try
                {
                    conn.Execute("nop");
                    false.IsEqualTo(true); // shouldn't have got here
                }
                catch
                {
                    conn.State.IsEqualTo(ConnectionState.Closed);
                }
            }
        }
1379 1380

        [Fact]
1381 1382 1383 1384 1385 1386 1387 1388 1389
        public void QueryFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                var i = conn.Query<int>("select 1").Single();
                conn.State.IsEqualTo(ConnectionState.Closed);
                i.IsEqualTo(1);
            }
        }
1390 1391

        [Fact]
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
        public void QueryInvalidFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                try
                {
                    conn.Query<int>("select gibberish").Single();
                    false.IsEqualTo(true); // shouldn't have got here
                }
                catch
                {
                    conn.State.IsEqualTo(ConnectionState.Closed);
                }
            }
        }
1407 1408

        [Fact]
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        public void QueryMultipleFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                using (var multi = conn.QueryMultiple("select 1; select 'abc';"))
                {
                    multi.Read<int>().Single().IsEqualTo(1);
                    multi.Read<string>().Single().IsEqualTo("abc");
                }
                conn.State.IsEqualTo(ConnectionState.Closed);
            }
        }
1421 1422

        [Fact]
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
        public void QueryMultipleInvalidFromClosed()
        {
            using (var conn = GetClosedConnection())
            {
                try
                {
                    conn.QueryMultiple("select gibberish");
                    false.IsEqualTo(true); // shouldn't have got here
                }
                catch
                {
                    conn.State.IsEqualTo(ConnectionState.Closed);
                }
            }
        }

1439
        [Fact]
1440 1441 1442 1443 1444 1445 1446 1447
        public void TestMultiSelectWithSomeEmptyGrids()
        {
            using (var reader = connection.QueryMultiple("select 1; select 2 where 1 = 0; select 3 where 1 = 0; select 4;"))
            {
                var one = reader.Read<int>().ToArray();
                var two = reader.Read<int>().ToArray();
                var three = reader.Read<int>().ToArray();
                var four = reader.Read<int>().ToArray();
1448 1449
                try
                { // only returned four grids; expect a fifth read to fail
1450 1451 1452
                    reader.Read<int>();
                    throw new InvalidOperationException("this should not have worked!");
                }
1453 1454
                catch (ObjectDisposedException ex)
                { // expected; success
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
                    ex.Message.IsEqualTo("The reader has been disposed; this can happen after all data has been consumed\r\nObject name: 'Dapper.SqlMapper+GridReader'.");
                }

                one.Length.IsEqualTo(1);
                one[0].IsEqualTo(1);
                two.Length.IsEqualTo(0);
                three.Length.IsEqualTo(0);
                four.Length.IsEqualTo(1);
                four[0].IsEqualTo(4);
            }
        }
1466

1467
        [Fact]
1468 1469 1470 1471
        public void TestDynamicMutation()
        {
            var obj = connection.Query("select 1 as [a], 2 as [b], 3 as [c]").Single();
            ((int)obj.a).IsEqualTo(1);
1472
            IDictionary<string, object> dict = obj;
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
            Assert.Equals(3, dict.Count);
            Assert.IsTrue(dict.Remove("a"));
            Assert.IsFalse(dict.Remove("d"));
            Assert.Equals(2, dict.Count);
            dict.Add("d", 4);
            Assert.Equals(3, dict.Count);
            Assert.Equals("b,c,d", string.Join(",", dict.Keys.OrderBy(x => x)));
            Assert.Equals("2,3,4", string.Join(",", dict.OrderBy(x => x.Key).Select(x => x.Value)));

            Assert.Equals(2, (int)obj.b);
            Assert.Equals(3, (int)obj.c);
            Assert.Equals(4, (int)obj.d);
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
            try
            {
                ((int)obj.a).IsEqualTo(1);
                throw new InvalidOperationException("should have thrown");
            }
            catch (RuntimeBinderException)
            {
                // pass
            }
        }
1495

1496 1497

        [Fact]
1498 1499 1500 1501
        public void TestIssue131()
        {
            var results = connection.Query<dynamic, int, dynamic>(
                "SELECT 1 Id, 'Mr' Title, 'John' Surname, 4 AddressCount",
N
Nigrimmist 已提交
1502
                (person, addressCount) => person,
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
                splitOn: "AddressCount"
            ).FirstOrDefault();

            var asDict = (IDictionary<string, object>)results;

            asDict.ContainsKey("Id").IsEqualTo(true);
            asDict.ContainsKey("Title").IsEqualTo(true);
            asDict.ContainsKey("Surname").IsEqualTo(true);
            asDict.ContainsKey("AddressCount").IsEqualTo(false);
        }
1513

1514
        // see http://stackoverflow.com/questions/16955357/issue-about-dapper
1515
        [Fact]
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
        public void TestSplitWithMissingMembers()
        {
            var result = connection.Query<Topic, Profile, Topic>(
            @"select 123 as ID, 'abc' as Title,
                     cast('01 Feb 2013' as datetime) as CreateDate,
                     'ghi' as Name, 'def' as Phone",
            (T, P) => { T.Author = P; return T; },
            null, null, true, "ID,Name").Single();

            result.ID.Equals(123);
            result.Title.Equals("abc");
            result.CreateDate.Equals(new DateTime(2013, 2, 1));
            result.Name.IsNull();
            result.Content.IsNull();

            result.Author.Phone.Equals("def");
            result.Author.Name.Equals("ghi");
            result.Author.ID.Equals(0);
            result.Author.Address.IsNull();
        }
        public class Profile
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Phone { get; set; }
            public string Address { get; set; }
            //public ExtraInfo Extra { get; set; }
        }

        public class Topic
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public DateTime CreateDate { get; set; }
            public string Content { get; set; }
            public int UID { get; set; }
            public int TestColum { get; set; }
            public string Name { get; set; }
            public Profile Author { get; set; }
            //public Attachment Attach { get; set; }
        }
1557 1558

        // see http://stackoverflow.com/questions/13127886/dapper-returns-null-for-singleordefaultdatediff
1559
        [Fact]
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
        public void TestNullFromInt_NoRows()
        {
            var result = connection.Query<int>( // case with rows
             "select DATEDIFF(day, GETUTCDATE(), @date)", new { date = DateTime.UtcNow.AddDays(20) })
             .SingleOrDefault();
            result.IsEqualTo(20);

            result = connection.Query<int>( // case without rows
                "select DATEDIFF(day, GETUTCDATE(), @date) where 1 = 0", new { date = DateTime.UtcNow.AddDays(20) })
                .SingleOrDefault();
            result.IsEqualTo(0); // zero rows; default of int over zero rows is zero


        }

1575
        [Fact]
1576 1577 1578
        public void TestChangingDefaultStringTypeMappingToAnsiString()
        {
            var sql = "SELECT SQL_VARIANT_PROPERTY(CONVERT(sql_variant, @testParam),'BaseType') AS BaseType";
1579
            var param = new { testParam = "TestString" };
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

            var result01 = connection.Query<string>(sql, param).FirstOrDefault();
            result01.IsEqualTo("nvarchar");

            Dapper.SqlMapper.PurgeQueryCache();

            Dapper.SqlMapper.AddTypeMap(typeof(string), DbType.AnsiString);   // Change Default String Handling to AnsiString
            var result02 = connection.Query<string>(sql, param).FirstOrDefault();
            result02.IsEqualTo("varchar");

            Dapper.SqlMapper.PurgeQueryCache();
            Dapper.SqlMapper.AddTypeMap(typeof(string), DbType.String);  // Restore Default to Unicode String
        }
1593

S
Sebastien Ros 已提交
1594
#if DOTNET5_2
M
Marc Gravell 已提交
1595 1596 1597 1598
        class TransactedConnection : IDbConnection
        {
            IDbConnection _conn;
            IDbTransaction _tran;
1599

M
Marc Gravell 已提交
1600 1601 1602 1603 1604
            public TransactedConnection(IDbConnection conn, IDbTransaction tran)
            {
                _conn = conn;
                _tran = tran;
            }
1605

M
Marc Gravell 已提交
1606
            public override string ConnectionString { get { return _conn.ConnectionString; } set { _conn.ConnectionString = value; } }
N
Nick Craver 已提交
1607 1608 1609
            public override int ConnectionTimeout => _conn.ConnectionTimeout;
            public override string Database => _conn.Database;
            public override ConnectionState State => _conn.State;
M
Marc Gravell 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

            protected override IDbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
            {
                return _tran;
            }
            
            public override void ChangeDatabase(string databaseName)
            {
                _conn.ChangeDatabase(databaseName);
            }
N
Nick Craver 已提交
1620 1621 1622 1623
            public override string DataSource => _conn.DataSource;

            public override string ServerVersion => _conn.ServerVersion;

M
Marc Gravell 已提交
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
            public override void Close()
            {
                _conn.Close();
            }
            protected override IDbCommand CreateDbCommand()
            {
                // The command inherits the "current" transaction.
                var command = _conn.CreateCommand();
                command.Transaction = _tran;
                return command;
            }

            protected override void Dispose(bool disposing)
            {
                if(disposing) _conn.Dispose();
                base.Dispose(disposing);
            }

            public override void Open()
            {
                _conn.Open();
            }
        }
#else
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
        class TransactedConnection : IDbConnection
        {
            IDbConnection _conn;
            IDbTransaction _tran;

            public TransactedConnection(IDbConnection conn, IDbTransaction tran)
            {
                _conn = conn;
                _tran = tran;
            }

            public string ConnectionString { get { return _conn.ConnectionString; } set { _conn.ConnectionString = value; } }
            public int ConnectionTimeout { get { return _conn.ConnectionTimeout; } }
            public string Database { get { return _conn.Database; } }
            public ConnectionState State { get { return _conn.State; } }

            public IDbTransaction BeginTransaction(IsolationLevel il)
            {
                throw new NotImplementedException();
            }

            public IDbTransaction BeginTransaction()
            {
                return _tran;
            }

            public void ChangeDatabase(string databaseName)
            {
                _conn.ChangeDatabase(databaseName);
            }

            public void Close()
            {
                _conn.Close();
            }

            public IDbCommand CreateCommand()
            {
                // The command inherits the "current" transaction.
                var command = _conn.CreateCommand();
                command.Transaction = _tran;
                return command;
            }

            public void Dispose()
            {
                _conn.Dispose();
            }

            public void Open()
            {
                _conn.Open();
            }
        }
M
Marc Gravell 已提交
1702
#endif
1703 1704

        [Fact]
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
        public void TestDapperTableMetadataRetrieval()
        {
            // Test for a bug found in CS 51509960 where the following sequence would result in an InvalidOperationException being
            // thrown due to an attempt to access a disposed of DataReader:
            //
            // - Perform a dynamic query that yields no results
            // - Add data to the source of that query
            // - Perform a the same query again
            connection.Execute("CREATE TABLE #sut (value varchar(10) NOT NULL PRIMARY KEY)");
            connection.Query("SELECT value FROM #sut").IsSequenceEqualTo(Enumerable.Empty<dynamic>());

            connection.Execute("INSERT INTO #sut (value) VALUES ('test')").IsEqualTo(1);
            var result = connection.Query("SELECT value FROM #sut");

            var first = result.First();
            ((string)first.value).IsEqualTo("test");
        }
D
Dave Peters 已提交
1722

1723
        [Fact]
1724 1725 1726 1727 1728
        public void TestIssue17648290()
        {
            var p = new DynamicParameters();
            int code = 1, getMessageControlId = 2;
            p.Add("@Code", code);
1729
            p.Add("@MessageControlID", getMessageControlId);
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
            p.Add("@SuccessCode", dbType: DbType.Int32, direction: ParameterDirection.Output);
            p.Add("@ErrorDescription", dbType: DbType.String, direction: ParameterDirection.Output, size: 255);
            connection.Execute(@"CREATE PROCEDURE #up_MessageProcessed_get
        @Code varchar(10),
        @MessageControlID varchar(22),
        @SuccessCode int OUTPUT,
        @ErrorDescription varchar(255) OUTPUT
        AS

        BEGIN

        Select 2 as MessageProcessID, 38349348 as StartNum, 3874900 as EndNum, GETDATE() as StartDate, GETDATE() as EndDate
        SET @SuccessCode = 0
        SET @ErrorDescription = 'Completed successfully'
        END");
            var result = connection.Query(sql: "#up_MessageProcessed_get", param: p, commandType: CommandType.StoredProcedure);
            var row = result.Single();
            ((int)row.MessageProcessID).IsEqualTo(2);
            ((int)row.StartNum).IsEqualTo(38349348);
            ((int)row.EndNum).IsEqualTo(3874900);
            DateTime startDate = row.StartDate, endDate = row.EndDate;
            p.Get<int>("SuccessCode").IsEqualTo(0);
            p.Get<string>("ErrorDescription").IsEqualTo("Completed successfully");
        }

1755
        [Fact]
1756 1757 1758 1759 1760 1761 1762 1763 1764
        public void TestDoubleDecimalConversions_SO18228523_RightWay()
        {
            var row = connection.Query<HasDoubleDecimal>(
                "select cast(1 as float) as A, cast(2 as float) as B, cast(3 as decimal) as C, cast(4 as decimal) as D").Single();
            row.A.Equals(1.0);
            row.B.Equals(2.0);
            row.C.Equals(3.0M);
            row.D.Equals(4.0M);
        }
1765 1766

        [Fact]
1767 1768 1769 1770 1771 1772 1773 1774 1775
        public void TestDoubleDecimalConversions_SO18228523_WrongWay()
        {
            var row = connection.Query<HasDoubleDecimal>(
                "select cast(1 as decimal) as A, cast(2 as decimal) as B, cast(3 as float) as C, cast(4 as float) as D").Single();
            row.A.Equals(1.0);
            row.B.Equals(2.0);
            row.C.Equals(3.0M);
            row.D.Equals(4.0M);
        }
1776 1777

        [Fact]
1778 1779 1780 1781 1782 1783 1784 1785 1786
        public void TestDoubleDecimalConversions_SO18228523_Nulls()
        {
            var row = connection.Query<HasDoubleDecimal>(
                "select cast(null as decimal) as A, cast(null as decimal) as B, cast(null as float) as C, cast(null as float) as D").Single();
            row.A.Equals(0.0);
            row.B.IsNull();
            row.C.Equals(0.0M);
            row.D.IsNull();
        }
1787
        
M
Marc Gravell 已提交
1788 1789
        private static CultureInfo ActiveCulture
        {
S
Sebastien Ros 已提交
1790
#if DOTNET5_2
M
Marc Gravell 已提交
1791 1792 1793 1794 1795 1796 1797
            get { return CultureInfo.CurrentCulture; }
            set { CultureInfo.CurrentCulture = value; }
#else
            get { return Thread.CurrentThread.CurrentCulture; }
            set { Thread.CurrentThread.CurrentCulture = value; }
#endif
        }
1798 1799

        [Fact]
1800 1801
        public void TestParameterInclusionNotSensitiveToCurrentCulture()
        {
M
Marc Gravell 已提交
1802
            // note this might fail if your database server is case-sensitive
M
Marc Gravell 已提交
1803
            CultureInfo current = ActiveCulture;
1804 1805
            try
            {
M
Marc Gravell 已提交
1806
                ActiveCulture = new CultureInfo("tr-TR");
1807

1808 1809 1810 1811
                connection.Query<int>("select @pid", new { PId = 1 }).Single();
            }
            finally
            {
M
Marc Gravell 已提交
1812
                ActiveCulture = current;
1813 1814
            }
        }
1815 1816

        [Fact]
1817 1818
        public void LiteralReplacement()
        {
1819
            connection.Execute("create table #literal1 (id int not null, foo int not null)");
1820
            connection.Execute("insert #literal1 (id,foo) values ({=id}, @foo)", new { id = 123, foo = 456 });
1821 1822
            var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } };
            connection.Execute("insert #literal1 (id,foo) values ({=id}, @foo)", rows);
1823 1824
            var count = connection.Query<int>("select count(1) from #literal1 where id={=foo}", new { foo = 123 }).Single();
            count.IsEqualTo(1);
1825 1826
            int sum = connection.Query<int>("select sum(id) + sum(foo) from #literal1").Single();
            sum.IsEqualTo(123 + 456 + 1 + 2 + 3 + 4);
1827
        }
1828 1829

        [Fact]
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
        public void LiteralReplacementDynamic()
        {
            var args = new DynamicParameters();
            args.Add("id", 123);
            connection.Execute("create table #literal2 (id int not null)");
            connection.Execute("insert #literal2 (id) values ({=id})", args);

            args = new DynamicParameters();
            args.Add("foo", 123);
            var count = connection.Query<int>("select count(1) from #literal2 where id={=foo}", args).Single();
            count.IsEqualTo(1);
        }
1842

1843 1844 1845 1846 1847
        enum AnEnum
        {
            A = 2,
            B = 1
        }
1848 1849 1850 1851 1852
        enum AnotherEnum : byte
        {
            A = 2,
            B = 1
        }
1853

S
Sebastien Ros 已提交
1854
#if DOTNET5_2
1855 1856
        [FrameworkFail("https://github.com/dotnet/corefx/issues/1613")]
#endif
1857
        [Fact]
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
        public void AdoNetEnumValue()
        {
            using (var cmd = connection.CreateCommand())
            {
                cmd.CommandText = "select @foo";
                cmd.Parameters.AddWithValue("@foo", AnEnum.B);
                object value = cmd.ExecuteScalar();
                AnEnum val = (AnEnum)value;
                val.IsEqualTo(AnEnum.B);
            }
        }

1870
        [Fact]
1871 1872
        public void LiteralReplacementEnumAndString()
        {
1873 1874
            var args = new { x = AnEnum.B, y = 123.45M, z = AnotherEnum.A };
            var row = connection.Query("select {=x} as x,{=y} as y,cast({=z} as tinyint) as z", args).Single();
1875 1876
            AnEnum x = (AnEnum)(int)row.x;
            decimal y = row.y;
1877
            AnotherEnum z = (AnotherEnum)(byte)row.z;
1878 1879
            x.Equals(AnEnum.B);
            y.Equals(123.45M);
1880
            z.Equals(AnotherEnum.A);
1881
        }
1882

1883
        [Fact]
1884 1885 1886 1887 1888
        public void LiteralReplacementDynamicEnumAndString()
        {
            var args = new DynamicParameters();
            args.Add("x", AnEnum.B);
            args.Add("y", 123.45M);
1889 1890
            args.Add("z", AnotherEnum.A);
            var row = connection.Query("select {=x} as x,{=y} as y,cast({=z} as tinyint) as z", args).Single();
1891 1892
            AnEnum x = (AnEnum)(int)row.x;
            decimal y = row.y;
1893
            AnotherEnum z = (AnotherEnum)(byte)row.z;
1894 1895
            x.Equals(AnEnum.B);
            y.Equals(123.45M);
1896 1897
            z.Equals(AnotherEnum.A);
        }
1898 1899

        [Fact]
1900 1901 1902 1903 1904 1905 1906 1907
        public void LiteralReplacementBoolean()
        {
            var row = connection.Query<int?>("select 42 where 1 = {=val}", new { val = true }).SingleOrDefault();
            row.IsNotNull();
            row.IsEqualTo(42);
            row = connection.Query<int?>("select 42 where 1 = {=val}", new { val = false }).SingleOrDefault();
            row.IsNull();
        }
1908 1909

        [Fact]
1910 1911 1912 1913 1914 1915 1916 1917 1918
        public void LiteralReplacementWithIn()
        {
            var data = connection.Query<MyRow>("select @x where 1 in @ids and 1 ={=a}",
                new { x = 1, ids = new[] { 1, 2, 3 }, a = 1 }).ToList();
        }

        class MyRow
        {
            public int x { get; set; }
1919 1920
        }

1921
        [Fact]
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
        public void LiteralIn()
        {
            connection.Execute("create table #literalin(id int not null);");
            connection.Execute("insert #literalin (id) values (@id)", new[] {
                new { id = 1 },
                new { id = 2 },
                new { id = 3 },
            });
            var count = connection.Query<int>("select count(1) from #literalin where id in {=ids}",
                new { ids = new[] { 1, 3, 4 } }).Single();
            count.IsEqualTo(2);
        }

1935
        [Fact]
1936
        public void DbStringAnsi()
M
Marc Gravell 已提交
1937 1938 1939 1940 1941 1942 1943 1944 1945
        {
            var a = connection.Query<int>("select datalength(@x)",
                new { x = new DbString { Value = "abc", IsAnsi = true } }).Single();
            var b = connection.Query<int>("select datalength(@x)",
                new { x = new DbString { Value = "abc", IsAnsi = false } }).Single();
            a.IsEqualTo(3);
            b.IsEqualTo(6);
        }

1946 1947 1948 1949
        class HasInt32
        {
            public int Value { get; set; }
        }
1950

1951
        // http://stackoverflow.com/q/23696254/23354
1952
        [Fact]
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
        public void DownwardIntegerConversion()
        {
            const string sql = "select cast(42 as bigint) as Value";
            int i = connection.Query<HasInt32>(sql).Single().Value;
            Assert.IsEqualTo(42, i);

            i = connection.Query<int>(sql).Single();
            Assert.IsEqualTo(42, i);
        }

1963 1964 1965 1966 1967 1968 1969
        class HasDoubleDecimal
        {
            public double A { get; set; }
            public double? B { get; set; }
            public decimal C { get; set; }
            public decimal? D { get; set; }
        }
1970 1971
        
        [Fact]
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
        public void GuidIn_SO_24177902()
        {
            // invent and populate
            Guid a = Guid.NewGuid(), b = Guid.NewGuid(), c = Guid.NewGuid(), d = Guid.NewGuid();
            connection.Execute("create table #foo (i int, g uniqueidentifier)");
            connection.Execute("insert #foo(i,g) values(@i,@g)",
                new[] { new { i = 1, g = a }, new { i = 2, g = b },
                new { i = 3, g = c },new { i = 4, g = d }});

            // check that rows 2&3 yield guids b&c
            var guids = connection.Query<Guid>("select g from #foo where i in (2,3)").ToArray();
            guids.Length.Equals(2);
            guids.Contains(a).Equals(false);
            guids.Contains(b).Equals(true);
            guids.Contains(c).Equals(true);
            guids.Contains(d).Equals(false);

            // in query on the guids
            var rows = connection.Query("select * from #foo where g in @guids order by i", new { guids })
                .Select(row => new { i = (int)row.i, g = (Guid)row.g }).ToArray();
            rows.Length.Equals(2);
            rows[0].i.Equals(2);
            rows[0].g.Equals(b);
            rows[1].i.Equals(3);
            rows[1].g.Equals(c);
        }
1998

1999
        [Fact]
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        public void TypeBasedViaDynamic()
        {
            Type type = GetSomeType();

            dynamic template = Activator.CreateInstance(type);
            dynamic actual = CheetViaDynamic(template, "select @A as [A], @B as [B]", new { A = 123, B = "abc" });
            ((object)actual).GetType().IsEqualTo(type);
            int a = actual.A;
            string b = actual.B;
            a.IsEqualTo(123);
            b.IsEqualTo("abc");
        }
2012 2013

        [Fact]
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
        public void TypeBasedViaType()
        {
            Type type = GetSomeType();

            dynamic actual = connection.Query(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).FirstOrDefault();
            ((object)actual).GetType().IsEqualTo(type);
            int a = actual.A;
            string b = actual.B;
            a.IsEqualTo(123);
            b.IsEqualTo("abc");
        }
2025 2026

        [Fact]
2027 2028 2029 2030 2031
        public void TypeBasedViaTypeMulti()
        {
            Type type = GetSomeType();

            dynamic first, second;
2032
            using (var multi = connection.QueryMultiple("select @A as [A], @B as [B]; select @C as [A], @D as [B]",
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
                new { A = 123, B = "abc", C = 456, D = "def" }))
            {
                first = multi.Read(type).Single();
                second = multi.Read(type).Single();
            }
            ((object)first).GetType().IsEqualTo(type);
            int a = first.A;
            string b = first.B;
            a.IsEqualTo(123);
            b.IsEqualTo("abc");

            ((object)second).GetType().IsEqualTo(type);
            a = second.A;
            b = second.B;
            a.IsEqualTo(456);
            b.IsEqualTo("def");
        }
2050 2051
        
        private T CheetViaDynamic<T>(T template, string query, object args)
2052 2053 2054 2055 2056 2057 2058 2059 2060
        {
            return connection.Query<T>(query, args).SingleOrDefault();
        }
        static Type GetSomeType()
        {
            return typeof(SomeType);
        }
        public class SomeType
        {
2061 2062
            public int A { get; set; }
            public string B { get; set; }
2063
        }
S
Sebastien Ros 已提交
2064
#if !DOTNET5_2
M
Marc Gravell 已提交
2065 2066 2067
        class WithInit : ISupportInitialize
        {
            public string Value { get; set; }
2068
            public int Flags { get; set; }
M
Marc Gravell 已提交
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079

            void ISupportInitialize.BeginInit()
            {
                Flags += 1;
            }

            void ISupportInitialize.EndInit()
            {
                Flags += 30;
            }
        }
M
Marc Gravell 已提交
2080
#endif
2081 2082

        [Fact]
M
Marc Gravell 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
        public void SO24607639_NullableBools()
        {
            var obj = connection.Query<HazBools>(
                @"declare @vals table (A bit null, B bit null, C bit null);
                insert @vals (A,B,C) values (1,0,null);
                select * from @vals").Single();
            obj.IsNotNull();
            obj.A.Value.IsEqualTo(true);
            obj.B.Value.IsEqualTo(false);
            obj.C.IsNull();
        }
        class HazBools
        {
            public bool? A { get; set; }
            public bool? B { get; set; }
            public bool? C { get; set; }
        }

2101
        [Fact]
M
Marc Gravell 已提交
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
        public void SO24605346_ProcsAndStrings()
        {
            connection.Execute(@"create proc #GetPracticeRebateOrderByInvoiceNumber @TaxInvoiceNumber nvarchar(20) as
                select @TaxInvoiceNumber as [fTaxInvoiceNumber]");
            string InvoiceNumber = "INV0000000028PPN";
            var result = connection.Query<PracticeRebateOrders>("#GetPracticeRebateOrderByInvoiceNumber", new
            {
                TaxInvoiceNumber = InvoiceNumber
            }, commandType: CommandType.StoredProcedure).FirstOrDefault();

            result.TaxInvoiceNumber.IsEqualTo("INV0000000028PPN");
        }
        class PracticeRebateOrders
        {
            public string fTaxInvoiceNumber;
M
Marc Gravell 已提交
2117
#if EXTERNALS
M
Marc Gravell 已提交
2118
            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
M
Marc Gravell 已提交
2119
#endif
M
Marc Gravell 已提交
2120 2121 2122
            public string TaxInvoiceNumber { get { return fTaxInvoiceNumber; } set { fTaxInvoiceNumber = value; } }
        }

2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
        public class RatingValueHandler : Dapper.SqlMapper.TypeHandler<RatingValue>
        {
            private RatingValueHandler() { }
            public static readonly RatingValueHandler Default = new RatingValueHandler();
            public override RatingValue Parse(object value)
            {
                if (value is Int32)
                    return new RatingValue() { Value = (Int32)value };

                throw new FormatException("Invalid conversion to RatingValue");
            }

M
Marc Gravell 已提交
2135
            public override void SetValue(IDbDataParameter parameter, RatingValue value)
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
            {
                // ... null, range checks etc ...
                parameter.DbType = System.Data.DbType.Int32;
                parameter.Value = value.Value;
            }
        }
        public class RatingValue
        {
            public Int32 Value { get; set; }
            // ... some other properties etc ...
        }

        public class MyResult
        {
            public String CategoryName { get; set; }
            public RatingValue CategoryRating { get; set; }
        }

2154
        [Fact]
2155 2156 2157 2158 2159 2160 2161 2162 2163
        public void SO24740733_TestCustomValueHandler()
        {
            Dapper.SqlMapper.AddTypeHandler(RatingValueHandler.Default);
            var foo = connection.Query<MyResult>("SELECT 'Foo' AS CategoryName, 200 AS CategoryRating").Single();

            foo.CategoryName.IsEqualTo("Foo");
            foo.CategoryRating.Value.IsEqualTo(200);
        }

B
Brann 已提交
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
        enum SO27024806Enum { Foo, Bar }

        private class SO27024806Class
        {
            public SO27024806Class(SO27024806Enum myField)
            {
                this.MyField = myField;
            }

            public SO27024806Enum MyField { get; set; }
        }

2176
        [Fact]
B
Brann 已提交
2177 2178 2179 2180 2181 2182 2183
        public void SO27024806_TestVarcharEnumMemberWithExplicitConstructor()
        {
            var foo = connection.Query<SO27024806Class>("SELECT 'Foo' AS myField").Single();
            foo.MyField.IsEqualTo(SO27024806Enum.Foo);
        }


2184
        [Fact]
2185 2186 2187 2188 2189 2190 2191 2192
        public void SO24740733_TestCustomValueSingleColumn()
        {
            Dapper.SqlMapper.AddTypeHandler(RatingValueHandler.Default);
            var foo = connection.Query<RatingValue>("SELECT 200 AS CategoryRating").Single();

            foo.Value.IsEqualTo(200);
        }

2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
        public class StringListTypeHandler : Dapper.SqlMapper.TypeHandler<List<String>>
        {
            private StringListTypeHandler() { }
            public static readonly StringListTypeHandler Default = new StringListTypeHandler();
            //Just a simple List<string> type handler implementation
            public override void SetValue(IDbDataParameter parameter, List<string> value)
            {
                parameter.Value = String.Join(",", value);
            }

            public override List<string> Parse(object value)
            {
                return ((value as String) ?? "").Split(',').ToList();
            }
        }
        public class MyObjectWithStringList
        {
            public List<String> Names { get; set; }
        }
2212 2213

        [Fact]
2214 2215 2216 2217 2218 2219 2220
        public void Issue253_TestIEnumerableTypeHandlerParsing()
        {
            Dapper.SqlMapper.ResetTypeHandlers();
            Dapper.SqlMapper.AddTypeHandler(StringListTypeHandler.Default);
            var foo = connection.Query<MyObjectWithStringList>("SELECT 'Sam,Kyro' AS Names").Single();
            foo.Names.IsSequenceEqualTo(new[] { "Sam", "Kyro" });
        }
2221 2222

        [Fact]
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
        public void Issue253_TestIEnumerableTypeHandlerSetParameterValue()
        {
            Dapper.SqlMapper.ResetTypeHandlers();
            Dapper.SqlMapper.AddTypeHandler(StringListTypeHandler.Default);

            connection.Execute("CREATE TABLE #Issue253 (Names VARCHAR(50) NOT NULL);");
            try
            {
                String names = "Sam,Kyro";
                List<String> names_list = names.Split(',').ToList();
                var foo = connection.Query<String>("INSERT INTO #Issue253 (Names) VALUES (@Names); SELECT Names FROM #Issue253;", new { Names = names_list }).Single();
                foo.IsEqualTo(names);
            }
            finally
            {
                connection.Execute("DROP TABLE #Issue253;");
            }
        }

2242
        [Fact]
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
        public void Issue130_IConvertible()
        {
            dynamic row = connection.Query("select 1 as [a], '2' as [b]").Single();
            int a = row.a;
            string b = row.b;
            a.IsEqualTo(1);
            b.IsEqualTo("2");

            row = connection.Query<dynamic>("select 3 as [a], '4' as [b]").Single();
            a = row.a;
            b = row.b;
            a.IsEqualTo(3);
            b.IsEqualTo("4");
        }

2258
        [Fact]
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
        public void Issue22_ExecuteScalar()
        {
            int i = connection.ExecuteScalar<int>("select 123");
            i.IsEqualTo(123);

            i = connection.ExecuteScalar<int>("select cast(123 as bigint)");
            i.IsEqualTo(123);

            long j = connection.ExecuteScalar<long>("select 123");
            j.IsEqualTo(123L);

            j = connection.ExecuteScalar<long>("select cast(123 as bigint)");
            j.IsEqualTo(123L);

            int? k = connection.ExecuteScalar<int?>("select @i", new { i = default(int?) });
            k.IsNull();

M
Marc Gravell 已提交
2276
#if EXTERNALS
2277 2278 2279 2280
            Dapper.EntityFramework.Handlers.Register();
            var geo = DbGeography.LineFromText("LINESTRING(-122.360 47.656, -122.343 47.656 )", 4326);
            var geo2 = connection.ExecuteScalar<DbGeography>("select @geo", new { geo });
            geo2.IsNotNull();
M
Marc Gravell 已提交
2281
#endif
2282 2283
        }

2284
        [Fact]
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
        public void Issue142_FailsNamedStatus()
        {
            var row1 = connection.Query<Issue142_Status>("select @Status as [Status]", new { Status = StatusType.Started }).Single();
            row1.Status.IsEqualTo(StatusType.Started);

            var row2 = connection.Query<Issue142_StatusType>("select @Status as [Status]", new { Status = Status.Started }).Single();
            row2.Status.IsEqualTo(Status.Started);
        }

        public class Issue142_Status
        {
            public StatusType Status { get; set; }
        }
        public class Issue142_StatusType
        {
            public Status Status { get; set; }
        }

        public enum StatusType : byte
        {
            NotStarted = 1, Started = 2, Finished = 3
        }
        public enum Status : byte
        {
            NotStarted = 1, Started = 2, Finished = 3
        }

2312
        [Fact]
2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
        public void Issue136_ValueTypeHandlers()
        {
            Dapper.SqlMapper.ResetTypeHandlers();
            Dapper.SqlMapper.AddTypeHandler(typeof(LocalDate), LocalDateHandler.Default);
            var param = new LocalDateResult
            {
                NotNullable = new LocalDate { Year = 2014, Month = 7, Day = 25 },
                NullableNotNull = new LocalDate { Year = 2014, Month = 7, Day = 26 },
                NullableIsNull = null,
            };

            var result = connection.Query<LocalDateResult>("SELECT @NotNullable AS NotNullable, @NullableNotNull AS NullableNotNull, @NullableIsNull AS NullableIsNull", param).Single();

            Dapper.SqlMapper.ResetTypeHandlers();
            Dapper.SqlMapper.AddTypeHandler(typeof(LocalDate?), LocalDateHandler.Default);
            result = connection.Query<LocalDateResult>("SELECT @NotNullable AS NotNullable, @NullableNotNull AS NullableNotNull, @NullableIsNull AS NullableIsNull", param).Single();
        }
2330

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
        public class LocalDateHandler : Dapper.SqlMapper.TypeHandler<LocalDate>
        {
            private LocalDateHandler() { }

            // Make the field type ITypeHandler to ensure it cannot be used with SqlMapper.AddTypeHandler<T>(TypeHandler<T>)
            // by mistake.
            public static readonly Dapper.SqlMapper.ITypeHandler Default = new LocalDateHandler();

            public override LocalDate Parse(object value)
            {
                var date = (DateTime)value;
                return new LocalDate { Year = date.Year, Month = date.Month, Day = date.Day };
            }

            public override void SetValue(IDbDataParameter parameter, LocalDate value)
            {
                parameter.DbType = DbType.DateTime;
                parameter.Value = new DateTime(value.Year, value.Month, value.Day);
            }
        }

        public struct LocalDate
        {
            public int Year { get; set; }
            public int Month { get; set; }
            public int Day { get; set; }
        }

        public class LocalDateResult
        {
            public LocalDate NotNullable { get; set; }
            public LocalDate? NullableNotNull { get; set; }
            public LocalDate? NullableIsNull { get; set; }
        }

2366 2367
        public class LotsOfNumerics
        {
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
            public enum E_Byte : byte { A = 0, B = 1 }
            public enum E_SByte : sbyte { A = 0, B = 1 }
            public enum E_Short : short { A = 0, B = 1 }
            public enum E_UShort : ushort { A = 0, B = 1 }
            public enum E_Int : int { A = 0, B = 1 }
            public enum E_UInt : uint { A = 0, B = 1 }
            public enum E_Long : long { A = 0, B = 1 }
            public enum E_ULong : ulong { A = 0, B = 1 }

            public E_Byte P_Byte { get; set; }
            public E_SByte P_SByte { get; set; }
            public E_Short P_Short { get; set; }
            public E_UShort P_UShort { get; set; }
            public E_Int P_Int { get; set; }
            public E_UInt P_UInt { get; set; }
            public E_Long P_Long { get; set; }
            public E_ULong P_ULong { get; set; }

            public bool N_Bool { get; set; }
            public byte N_Byte { get; set; }
            public sbyte N_SByte { get; set; }
            public short N_Short { get; set; }
            public ushort N_UShort { get; set; }
            public int N_Int { get; set; }
            public uint N_UInt { get; set; }
            public long N_Long { get; set; }
            public ulong N_ULong { get; set; }

            public float N_Float { get; set; }
            public double N_Double { get; set; }
            public decimal N_Decimal { get; set; }
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421

            public E_Byte? N_P_Byte { get; set; }
            public E_SByte? N_P_SByte { get; set; }
            public E_Short? N_P_Short { get; set; }
            public E_UShort? N_P_UShort { get; set; }
            public E_Int? N_P_Int { get; set; }
            public E_UInt? N_P_UInt { get; set; }
            public E_Long? N_P_Long { get; set; }
            public E_ULong? N_P_ULong { get; set; }

            public bool? N_N_Bool { get; set; }
            public byte? N_N_Byte { get; set; }
            public sbyte? N_N_SByte { get; set; }
            public short? N_N_Short { get; set; }
            public ushort? N_N_UShort { get; set; }
            public int? N_N_Int { get; set; }
            public uint? N_N_UInt { get; set; }
            public long? N_N_Long { get; set; }
            public ulong? N_N_ULong { get; set; }

            public float? N_N_Float { get; set; }
            public double? N_N_Double { get; set; }
            public decimal? N_N_Decimal { get; set; }
2422 2423
        }

2424
        [Fact]
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
        public void TestBigIntForEverythingWorks_SqlLite()
        {
            TestBigIntForEverythingWorks_SqlLite_ByDataType<long>("bigint");
            TestBigIntForEverythingWorks_SqlLite_ByDataType<int>("int");
            TestBigIntForEverythingWorks_SqlLite_ByDataType<byte>("tinyint");
            TestBigIntForEverythingWorks_SqlLite_ByDataType<short>("smallint");
            TestBigIntForEverythingWorks_SqlLite_ByDataType<bool>("bit");
            TestBigIntForEverythingWorks_SqlLite_ByDataType<float>("float(24)");
            TestBigIntForEverythingWorks_SqlLite_ByDataType<double>("float(53)");
        }
2435
        
2436 2437
        private void TestBigIntForEverythingWorks_SqlLite_ByDataType<T>(string dbType)
        {
2438
            using (var reader = connection.ExecuteReader("select cast(1 as " + dbType + ")"))
2439 2440 2441 2442 2443 2444
            {
                reader.Read().IsTrue();
                reader.GetFieldType(0).Equals(typeof(T));
                reader.Read().IsFalse();
                reader.NextResult().IsFalse();
            }
2445

2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
            string sql = "select " + string.Join(",", typeof(LotsOfNumerics).GetProperties().Select(
                x => "cast (1 as " + dbType + ") as [" + x.Name + "]"));
            var row = connection.Query<LotsOfNumerics>(sql).Single();

            row.N_Bool.IsTrue();
            row.N_SByte.IsEqualTo((sbyte)1);
            row.N_Byte.IsEqualTo((byte)1);
            row.N_Int.IsEqualTo((int)1);
            row.N_UInt.IsEqualTo((uint)1);
            row.N_Short.IsEqualTo((short)1);
            row.N_UShort.IsEqualTo((ushort)1);
            row.N_Long.IsEqualTo((long)1);
            row.N_ULong.IsEqualTo((ulong)1);
            row.N_Float.IsEqualTo((float)1);
            row.N_Double.IsEqualTo((double)1);
            row.N_Decimal.IsEqualTo((decimal)1);

            row.P_Byte.IsEqualTo(LotsOfNumerics.E_Byte.B);
            row.P_SByte.IsEqualTo(LotsOfNumerics.E_SByte.B);
            row.P_Short.IsEqualTo(LotsOfNumerics.E_Short.B);
            row.P_UShort.IsEqualTo(LotsOfNumerics.E_UShort.B);
            row.P_Int.IsEqualTo(LotsOfNumerics.E_Int.B);
            row.P_UInt.IsEqualTo(LotsOfNumerics.E_UInt.B);
            row.P_Long.IsEqualTo(LotsOfNumerics.E_Long.B);
            row.P_ULong.IsEqualTo(LotsOfNumerics.E_ULong.B);

2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
            row.N_N_Bool.Value.IsTrue();
            row.N_N_SByte.Value.IsEqualTo((sbyte)1);
            row.N_N_Byte.Value.IsEqualTo((byte)1);
            row.N_N_Int.Value.IsEqualTo((int)1);
            row.N_N_UInt.Value.IsEqualTo((uint)1);
            row.N_N_Short.Value.IsEqualTo((short)1);
            row.N_N_UShort.Value.IsEqualTo((ushort)1);
            row.N_N_Long.Value.IsEqualTo((long)1);
            row.N_N_ULong.Value.IsEqualTo((ulong)1);
            row.N_N_Float.Value.IsEqualTo((float)1);
            row.N_N_Double.Value.IsEqualTo((double)1);
            row.N_N_Decimal.IsEqualTo((decimal)1);

            row.N_P_Byte.Value.IsEqualTo(LotsOfNumerics.E_Byte.B);
            row.N_P_SByte.Value.IsEqualTo(LotsOfNumerics.E_SByte.B);
            row.N_P_Short.Value.IsEqualTo(LotsOfNumerics.E_Short.B);
            row.N_P_UShort.Value.IsEqualTo(LotsOfNumerics.E_UShort.B);
            row.N_P_Int.Value.IsEqualTo(LotsOfNumerics.E_Int.B);
            row.N_P_UInt.Value.IsEqualTo(LotsOfNumerics.E_UInt.B);
            row.N_P_Long.Value.IsEqualTo(LotsOfNumerics.E_Long.B);
            row.N_P_ULong.Value.IsEqualTo(LotsOfNumerics.E_ULong.B);

2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
            TestBigIntForEverythingWorks<bool>(true, dbType);
            TestBigIntForEverythingWorks<sbyte>((sbyte)1, dbType);
            TestBigIntForEverythingWorks<byte>((byte)1, dbType);
            TestBigIntForEverythingWorks<int>((int)1, dbType);
            TestBigIntForEverythingWorks<uint>((uint)1, dbType);
            TestBigIntForEverythingWorks<short>((short)1, dbType);
            TestBigIntForEverythingWorks<ushort>((ushort)1, dbType);
            TestBigIntForEverythingWorks<long>((long)1, dbType);
            TestBigIntForEverythingWorks<ulong>((ulong)1, dbType);
            TestBigIntForEverythingWorks<float>((float)1, dbType);
            TestBigIntForEverythingWorks<double>((double)1, dbType);
            TestBigIntForEverythingWorks<decimal>((decimal)1, dbType);

            TestBigIntForEverythingWorks(LotsOfNumerics.E_Byte.B, dbType);
            TestBigIntForEverythingWorks(LotsOfNumerics.E_SByte.B, dbType);
            TestBigIntForEverythingWorks(LotsOfNumerics.E_Int.B, dbType);
            TestBigIntForEverythingWorks(LotsOfNumerics.E_UInt.B, dbType);
            TestBigIntForEverythingWorks(LotsOfNumerics.E_Short.B, dbType);
2512
            TestBigIntForEverythingWorks(LotsOfNumerics.E_UShort.B, dbType);
2513 2514
            TestBigIntForEverythingWorks(LotsOfNumerics.E_Long.B, dbType);
            TestBigIntForEverythingWorks(LotsOfNumerics.E_ULong.B, dbType);
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536

            TestBigIntForEverythingWorks<bool?>(true, dbType);
            TestBigIntForEverythingWorks<sbyte?>((sbyte)1, dbType);
            TestBigIntForEverythingWorks<byte?>((byte)1, dbType);
            TestBigIntForEverythingWorks<int?>((int)1, dbType);
            TestBigIntForEverythingWorks<uint?>((uint)1, dbType);
            TestBigIntForEverythingWorks<short?>((short)1, dbType);
            TestBigIntForEverythingWorks<ushort?>((ushort)1, dbType);
            TestBigIntForEverythingWorks<long?>((long)1, dbType);
            TestBigIntForEverythingWorks<ulong?>((ulong)1, dbType);
            TestBigIntForEverythingWorks<float?>((float)1, dbType);
            TestBigIntForEverythingWorks<double?>((double)1, dbType);
            TestBigIntForEverythingWorks<decimal?>((decimal)1, dbType);

            TestBigIntForEverythingWorks<LotsOfNumerics.E_Byte?>(LotsOfNumerics.E_Byte.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_SByte?>(LotsOfNumerics.E_SByte.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_Int?>(LotsOfNumerics.E_Int.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_UInt?>(LotsOfNumerics.E_UInt.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_Short?>(LotsOfNumerics.E_Short.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_UShort?>(LotsOfNumerics.E_UShort.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_Long?>(LotsOfNumerics.E_Long.B, dbType);
            TestBigIntForEverythingWorks<LotsOfNumerics.E_ULong?>(LotsOfNumerics.E_ULong.B, dbType);
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
        }

        private void TestBigIntForEverythingWorks<T>(T expected, string dbType)
        {
            var query = connection.Query<T>("select cast(1 as " + dbType + ")").Single();
            query.IsEqualTo(expected);

            var scalar = connection.ExecuteScalar<T>("select cast(1 as " + dbType + ")");
            scalar.IsEqualTo(expected);
        }

2548
        [Fact]
2549 2550 2551
        public void TestSubsequentQueriesSuccess()
        {
            var data0 = connection.Query<Fooz0>("select 1 as [Id] where 1 = 0").ToList();
2552
            data0.Count.IsEqualTo(0);
2553 2554

            var data1 = connection.Query<Fooz1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ToList();
2555
            data1.Count.IsEqualTo(0);
2556 2557

            var data2 = connection.Query<Fooz2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ToList();
2558
            data2.Count.IsEqualTo(0);
2559 2560

            data0 = connection.Query<Fooz0>("select 1 as [Id] where 1 = 0").ToList();
2561
            data0.Count.IsEqualTo(0);
2562 2563

            data1 = connection.Query<Fooz1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ToList();
2564
            data1.Count.IsEqualTo(0);
2565 2566

            data2 = connection.Query<Fooz2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ToList();
2567
            data2.Count.IsEqualTo(0);
2568 2569 2570 2571
        }
        class Fooz0 { public int Id { get; set; } }
        class Fooz1 { public int Id { get; set; } }
        class Fooz2 { public int Id { get; set; } }
2572

2573

2574
        [Fact]
2575 2576 2577 2578 2579 2580 2581 2582
        public void Issue149_TypeMismatch_SequentialAccess()
        {
            string error;
            Guid guid = Guid.Parse("cf0ef7ac-b6fe-4e24-aeda-a2b45bb5654e");
            try
            {
                var result = connection.Query<Issue149_Person>(@"select @guid as Id", new { guid }).First();
                error = null;
2583 2584
            }
            catch (Exception ex)
2585 2586 2587 2588 2589 2590
            {
                error = ex.Message;
            }
            error.IsEqualTo("Error parsing column 0 (Id=cf0ef7ac-b6fe-4e24-aeda-a2b45bb5654e - Object)");
        }
        public class Issue149_Person { public string Id { get; set; } }
2591

2592 2593 2594 2595 2596
        public class HazX
        {
            public string X { get; set; }
        }

2597
        [Fact]
2598 2599 2600
        public void Issue178_SqlServer()
        {
            const string sql = @"select count(*) from Issue178";
2601 2602 2603 2604
            try { connection.Execute("drop table Issue178"); }
            catch { }
            try { connection.Execute("create table Issue178(id int not null)"); }
            catch { }
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
            // raw ADO.net
            var sqlCmd = new SqlCommand(sql, connection);
            using (IDataReader reader1 = sqlCmd.ExecuteReader())
            {
                Assert.IsTrue(reader1.Read());
                reader1.GetInt32(0).IsEqualTo(0);
                Assert.IsFalse(reader1.Read());
                Assert.IsFalse(reader1.NextResult());
            }

            // dapper
            using (var reader2 = connection.ExecuteReader(sql))
            {
                Assert.IsTrue(reader2.Read());
                reader2.GetInt32(0).IsEqualTo(0);
                Assert.IsFalse(reader2.Read());
                Assert.IsFalse(reader2.NextResult());
            }
        }
M
Marc Gravell 已提交
2624
#if EXTERNALS
2625
        [SkipTest]
2626 2627 2628 2629 2630 2631 2632 2633
        public void Issue178_Firebird() // we expect this to fail due to a bug in Firebird; a PR to fix it has been submitted
        {
            var cs = @"initial catalog=localhost:database;user id=SYSDBA;password=masterkey";

            using (var connection = new FbConnection(cs))
            {
                connection.Open();
                const string sql = @"select count(*) from Issue178";
2634 2635
                try { connection.Execute("drop table Issue178"); }
                catch { }
2636 2637
                connection.Execute("create table Issue178(id int not null)");
                connection.Execute("insert into Issue178(id) values(42)");
2638
                // raw ADO.net
2639
                using (var sqlCmd = new FbCommand(sql, connection))
2640 2641 2642
                using (IDataReader reader1 = sqlCmd.ExecuteReader())
                {
                    Assert.IsTrue(reader1.Read());
2643
                    reader1.GetInt32(0).IsEqualTo(1);
2644 2645 2646 2647 2648 2649 2650 2651
                    Assert.IsFalse(reader1.Read());
                    Assert.IsFalse(reader1.NextResult());
                }

                // dapper
                using (var reader2 = connection.ExecuteReader(sql))
                {
                    Assert.IsTrue(reader2.Read());
2652
                    reader2.GetInt32(0).IsEqualTo(1);
2653 2654 2655
                    Assert.IsFalse(reader2.Read());
                    Assert.IsFalse(reader2.NextResult());
                }
2656 2657 2658

                var count = connection.Query<int>(sql).Single();
                count.IsEqualTo(1);
2659 2660
            }
        }
2661 2662
        
        [Fact]
2663 2664 2665 2666 2667 2668 2669 2670
        public void PseudoPositionalParameters_Simple()
        {
            using (var connection = ConnectViaOledb())
            {
                int value = connection.Query<int>("select ?x? + ?y_2? + ?z?", new { x = 1, y_2 = 3, z = 5, z2 = 24 }).Single();
                value.IsEqualTo(9);
            }
        }
2671 2672
        
        [Fact]
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
        public void PseudoPositionalParameters_Dynamic()
        {
            using (var connection = ConnectViaOledb())
            {
                var args = new DynamicParameters();
                args.Add("x", 1);
                args.Add("y_2", 3);
                args.Add("z", 5);
                args.Add("z2", 24);
                int value = connection.Query<int>("select ?x? + ?y_2? + ?z?", args).Single();
                value.IsEqualTo(9);
            }
        }
2686 2687
        
        [Fact]
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
        public void PseudoPositionalParameters_ReusedParameter()
        {
            using (var connection = ConnectViaOledb())
            {
                try
                {
                    int value = connection.Query<int>("select ?x? + ?y_2? + ?x?", new { x = 1, y_2 = 3 }).Single();
                    Assert.Fail();
                }
                catch (InvalidOperationException ex)
                {
                    ex.Message.IsEqualTo("When passing parameters by position, each parameter can only be referenced once");
                }
            }
        }
2703 2704
        
        [Fact]
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
        public void PseudoPositionalParameters_ExecSingle()
        {
            using (var connection = ConnectViaOledb())
            {
                var data = new { x = 6 };
                connection.Execute("create table #named_single(val int not null)");
                int count = connection.Execute("insert #named_single (val) values (?x?)", data);
                int sum = (int)connection.ExecuteScalar("select sum(val) from #named_single");
                count.IsEqualTo(1);
                sum.IsEqualTo(6);
            }
        }
2717 2718
        
        [Fact]
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
        public void PseudoPositionalParameters_ExecMulti()
        {
            using (var connection = ConnectViaOledb())
            {
                var data = new[]
                {
                    new { x = 1, y = 1 },
                    new { x = 3, y = 1 },
                    new { x = 6, y = 1 },
                };
                connection.Execute("create table #named_multi(val int not null)");
                int count = connection.Execute("insert #named_multi (val) values (?x?)", data);
                int sum = (int)connection.ExecuteScalar("select sum(val) from #named_multi");
                count.IsEqualTo(3);
                sum.IsEqualTo(10);
            }
        }
M
Marc Gravell 已提交
2736
#endif
2737 2738

        [Fact]
2739 2740 2741 2742 2743 2744
        public void QueryBasicWithoutQuery()
        {
            int? i = connection.Query<int?>("print 'not a query'").FirstOrDefault();
            i.IsNull();
        }

2745
        [Fact]
2746 2747 2748 2749 2750 2751
        public void QueryComplexWithoutQuery()
        {
            var obj = connection.Query<Foo1>("print 'not a query'").FirstOrDefault();
            obj.IsNull();
        }

2752
        [Fact]
2753 2754 2755 2756 2757 2758 2759 2760
        public void SO29343103_UtcDates()
        {
            const string sql = "select @date";
            var date = DateTime.UtcNow;
            var returned = connection.Query<DateTime>(sql, new { date }).Single();
            var delta = returned - date;
            Assert.IsTrue(delta.TotalMilliseconds >= -1 && delta.TotalMilliseconds <= 1);
        }
S
Sebastien Ros 已提交
2761
#if DOTNET5_2
2762 2763
        [FrameworkFail("https://github.com/dotnet/corefx/issues/1612")]
#endif
2764
        [Fact]
2765 2766 2767 2768 2769 2770 2771 2772 2773
        public void Issue261_Decimals()
        {
            var parameters = new DynamicParameters();
            parameters.Add("c", dbType: DbType.Decimal, direction: ParameterDirection.Output, precision: 10, scale: 5);
            connection.Execute("create proc #Issue261 @c decimal(10,5) OUTPUT as begin set @c=11.884 end");
            connection.Execute("#Issue261", parameters, commandType: CommandType.StoredProcedure);
            var c = parameters.Get<Decimal>("c");
            c.IsEqualTo(11.884M);
        }
S
Sebastien Ros 已提交
2774
#if DOTNET5_2
2775 2776
        [FrameworkFail("https://github.com/dotnet/corefx/issues/1612")]
#endif
2777
        [Fact]
2778 2779 2780 2781 2782
        public void Issue261_Decimals_ADONET_SetViaBaseClass()
        {
            Issue261_Decimals_ADONET(true);
        }

2783
        [Fact]
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
        public void Issue261_Decimals_ADONET_SetViaConcreteClass()
        {
            Issue261_Decimals_ADONET(false);
        }
        private void Issue261_Decimals_ADONET(bool setPrecisionScaleViaAbstractApi)
        {
            try
            {
                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = "create proc #Issue261Direct @c decimal(10,5) OUTPUT as begin set @c=11.884 end";
                    cmd.ExecuteNonQuery();
                }
            }
            catch { /* we don't care that it already exists */ }

            using (var cmd = connection.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "#Issue261Direct";
                var c = cmd.CreateParameter();
                c.ParameterName = "c";
                c.Direction = ParameterDirection.Output;
                c.Value = DBNull.Value;
                c.DbType = DbType.Decimal;

                if (setPrecisionScaleViaAbstractApi)
                {
                    IDbDataParameter baseParam = c;
                    baseParam.Precision = 10;
                    baseParam.Scale = 5;
                }
                else
                {
                    c.Precision = 10;
                    c.Scale = 5;
                }

                cmd.Parameters.Add(c);
                cmd.ExecuteNonQuery();
                decimal value = (decimal)c.Value;
                value.IsEqualTo(11.884M);
            }
        }
2828

2829
        [Fact]
2830 2831 2832 2833
        public void BasicDecimals()
        {
            var c = connection.Query<decimal>("select @c", new { c = 11.884M }).Single();
            c.IsEqualTo(11.884M);
2834
        }
2835

M
Marc Gravell 已提交
2836
        [SkipTest]
2837 2838 2839 2840 2841 2842 2843 2844
        public void Issue263_Timeout()
        {
            var watch = Stopwatch.StartNew();
            var i = connection.Query<int>("waitfor delay '00:01:00'; select 42;", commandTimeout: 300, buffered: false).Single();
            watch.Stop();
            i.IsEqualTo(42);
            var minutes = watch.ElapsedMilliseconds / 1000 / 60;
            Assert.IsTrue(minutes >= 0.95 && minutes <= 1.05);
2845
        }
M
Marc Gravell 已提交
2846
#if EXTERNALS
2847
        [Fact]
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
        public void SO29596645_TvpProperty()
        {
            try { connection.Execute("CREATE TYPE SO29596645_ReminderRuleType AS TABLE (id int NOT NULL)"); }
            catch { }
            connection.Execute(@"create proc #SO29596645_Proc (@Id int, @Rules SO29596645_ReminderRuleType READONLY)
                                as begin select @Id + ISNULL((select sum(id) from @Rules), 0); end");
            var obj = new SO29596645_OrganisationDTO();
            int val = connection.Query<int>("#SO29596645_Proc", obj.Rules, commandType: CommandType.StoredProcedure).Single();

            // 4 + 9 + 7 = 20
            val.IsEqualTo(20);

        }
M
Marc Gravell 已提交
2861 2862
#endif
#if EXTERNALS
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
        class SO29596645_RuleTableValuedParameters : Dapper.SqlMapper.IDynamicParameters {
            private string parameterName;

            public SO29596645_RuleTableValuedParameters(string parameterName)
            {
                this.parameterName = parameterName;
            }


            public void AddParameters(IDbCommand command, Dapper.SqlMapper.Identity identity)
            {
                Console.WriteLine("> AddParameters");
                SqlCommand lazy = (SqlCommand)command;
                lazy.Parameters.AddWithValue("Id", 7);
                DataTable table = new DataTable {
                    Columns = {{"Id", typeof(int)}},
                    Rows = {{4}, {9}}
                };
                lazy.Parameters.AddWithValue("Rules", table);
                Console.WriteLine("< AddParameters");
            }
        }
        class SO29596645_OrganisationDTO
        {
            public SO29596645_RuleTableValuedParameters Rules { get; private set; }

            public SO29596645_OrganisationDTO()
            {
                Rules = new SO29596645_RuleTableValuedParameters("@Rules");
            }
        }
M
Marc Gravell 已提交
2894
#endif
2895
#if POSTGRESQL
2896

2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
        class Cat
        {
            public int Id { get; set; }
            public string Breed { get; set; }
            public string Name { get; set; }
        }

        Cat[] Cats = {
                                new Cat() { Breed = "Abyssinian", Name="KACTUS"},
                                new Cat() { Breed = "Aegean cat", Name="KADAFFI"},
                                new Cat() { Breed = "American Bobtail", Name="KANJI"},
                                new Cat() { Breed = "Balinese", Name="MACARONI"},
                                new Cat() { Breed = "Bombay", Name="MACAULAY"},
                                new Cat() { Breed = "Burmese", Name="MACBETH"},
                                new Cat() { Breed = "Chartreux", Name="MACGYVER"},
                                new Cat() { Breed = "German Rex", Name="MACKENZIE"},
                                new Cat() { Breed = "Javanese", Name="MADISON"},
                                new Cat() { Breed = "Persian", Name="MAGNA"}
                            };
2916 2917
        
        [Fact]
2918 2919 2920 2921 2922 2923 2924
        public void TestPostresqlArrayParameters()
        {
            using (var conn = new NpgsqlConnection("Server=localhost;Port=5432;User Id=dappertest;Password=dapperpass;Database=dappertest;Encoding=UNICODE"))
            {
                conn.Open();
                IDbTransaction transaction = conn.BeginTransaction();
                conn.Execute("create table tcat ( id serial not null, breed character varying(20) not null, name character varying (20) not null);");
J
John Grant 已提交
2925
                conn.Execute("insert into tcat(breed, name) values(:breed, :name) ", Cats);
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935

                var r = conn.Query<Cat>("select * from tcat where id=any(:catids)", new { catids = new[] { 1, 3, 5 } });
                r.Count().IsEqualTo(3);
                r.Count(c => c.Id == 1).IsEqualTo(1);
                r.Count(c => c.Id == 3).IsEqualTo(1);
                r.Count(c => c.Id == 5).IsEqualTo(1);
                transaction.Rollback();
            }
        }
#endif
2936

2937
        [Fact]
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
        public void SO30435185_InvalidTypeOwner()
        {
            try {
                string sql = @" INSERT INTO #XXX
                        (XXXId, AnotherId, ThirdId, Value, Comment)
                        VALUES
                        (@XXXId, @AnotherId, @ThirdId, @Value, @Comment); select @@rowcount as [Foo]";

                var command = new
                {
                    MyModels = new[]
                    {
                        new {XXXId = 1, AnotherId = 2, ThirdId = 3, Value = "abc", Comment = "def" }
                }
                };
                var parameters = command
                    .MyModels
                    .Select(model => new
                    {
                        XXXId = model.XXXId,
                        AnotherId = model.AnotherId,
                        ThirdId = model.ThirdId,
                        Value = model.Value,
                        Comment = model.Comment
                    })
                    .ToArray();

                var rowcount = (int)connection.Query(sql, parameters).Single().Foo;
                rowcount.IsEqualTo(1);

                Assert.Fail();
            } catch(InvalidOperationException ex)
            {
                ex.Message.IsEqualTo("An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context");
            }
        }
S
Sam Saffron 已提交
2974 2975
    }
}