Commit 702c918b authored by Nick Craver's avatar Nick Craver Committed by GitHub

Merge branch 'master' into master

parents e1fdc3bd 6ce36492
......@@ -5,7 +5,7 @@
<Title>Dapper.Contrib</Title>
<Description>The official collection of get, insert, update and delete helpers for Dapper.net. Also handles lists of entities and optional "dirty" tracking of interface-based entities.</Description>
<Authors>Sam Saffron;Johan Danforth</Authors>
<TargetFrameworks>net40;net45;netstandard1.3</TargetFrameworks>
<TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
<!-- TODO: Docs -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
......@@ -15,7 +15,7 @@
<ItemGroup>
<ProjectReference Include="..\Dapper\Dapper.csproj" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq" />
<Reference Include="System" />
......
......@@ -9,7 +9,7 @@
using Dapper;
#if COREFX
#if NETSTANDARD1_3
using DataException = System.InvalidOperationException;
#else
using System.Threading;
......@@ -274,7 +274,7 @@ private static string GetTableName(Type type)
{
//NOTE: This as dynamic trick should be able to handle both our own Table-attribute as well as the one in EntityFramework
var tableAttr = type
#if COREFX
#if NETSTANDARD1_3
.GetTypeInfo()
#endif
.GetCustomAttributes(false).SingleOrDefault(attr => attr.GetType().Name == "TableAttribute") as dynamic;
......@@ -516,7 +516,7 @@ private static class ProxyGenerator
private static AssemblyBuilder GetAsmBuilder(string name)
{
#if COREFX
#if NETSTANDARD1_3
return AssemblyBuilder.DefineDynamicAssembly(new AssemblyName { Name = name }, AssemblyBuilderAccess.Run);
#else
return Thread.GetDomain().DefineDynamicAssembly(new AssemblyName { Name = name }, AssemblyBuilderAccess.Run);
......@@ -551,7 +551,7 @@ public static T GetInterfaceProxy<T>()
CreateProperty<T>(typeBuilder, property.Name, property.PropertyType, setIsDirtyMethod, isId);
}
#if COREFX
#if NETSTANDARD1_3
var generatedType = typeBuilder.CreateTypeInfo().AsType();
#else
var generatedType = typeBuilder.CreateType();
......
......@@ -4,7 +4,7 @@
<Title>Dapper: Entity Framework type handlers (with a strong name)</Title>
<Description>Extension handlers for entity framework</Description>
<Authors>Marc Gravell;Nick Craver</Authors>
<TargetFrameworks>net40;net45</TargetFrameworks>
<TargetFrameworks>net451</TargetFrameworks>
<AssemblyOriginatorKeyFile>../Dapper.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
......
......@@ -5,7 +5,7 @@
<AssemblyTitle>Dapper entity framework type handlers</AssemblyTitle>
<VersionPrefix>1.50.2</VersionPrefix>
<Authors>Marc Gravell;Nick Craver</Authors>
<TargetFrameworks>net40;net45</TargetFrameworks>
<TargetFrameworks>net451</TargetFrameworks>
<PackageTags>orm;sql;micro-orm</PackageTags>
</PropertyGroup>
<ItemGroup>
......
......@@ -6,7 +6,7 @@
<Description>Trivial micro-orm implemented on Dapper, provides with CRUD helpers.</Description>
<Authors>Sam Saffron</Authors>
<Copyright>2017 Sam Saffron</Copyright>
<TargetFrameworks>net40;net45;netstandard1.3</TargetFrameworks>
<TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
<!-- TODO: Docs -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
......@@ -16,14 +16,14 @@
<ItemGroup>
<ProjectReference Include="..\Dapper\Dapper.csproj" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq" />
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.3'">
<PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
</ItemGroup>
</Project>
\ No newline at end of file
......@@ -5,7 +5,7 @@
<Title>Dapper SqlBuilder component</Title>
<Description>The Dapper SqlBuilder component, for building SQL queries dynamically.</Description>
<Authors>Sam Saffron, Johan Danforth</Authors>
<TargetFrameworks>net40;net45;netstandard1.3</TargetFrameworks>
<TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
<!-- TODO: Docs -->
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
......@@ -13,13 +13,13 @@
<ItemGroup>
<ProjectReference Include="..\Dapper\Dapper.csproj" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq" />
<Reference Include="System" />
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.3'">
<PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
</ItemGroup>
</Project>
\ No newline at end of file
......@@ -5,14 +5,14 @@
<Title>Dapper (Strong Named)</Title>
<Description>A high performance Micro-ORM supporting SQL Server, MySQL, Sqlite, SqlCE, Firebird etc..</Description>
<Authors>Sam Saffron;Marc Gravell;Nick Craver</Authors>
<TargetFrameworks>net40;net45;net451;netstandard1.3</TargetFrameworks>
<TargetFrameworks>net451;netstandard1.3;netstandard2.0</TargetFrameworks>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\Dapper\**\*.cs" Exclude="..\Dapper\obj\**\*.cs" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' OR '$(TargetFramework)' == 'net451' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
......@@ -22,7 +22,7 @@
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<PackageReference Include="System.Collections.Concurrent" Version="4.3.0" />
<PackageReference Include="System.Collections.NonGeneric" Version="4.3.0" />
<PackageReference Include="System.Data.Common" Version="4.3.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<PackageReference Include="System.Dynamic.Runtime" Version="4.3.0" />
<PackageReference Include="System.Reflection.Emit" Version="4.3.0" />
<PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" />
......@@ -30,4 +30,9 @@
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" />
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.4.0" />
</ItemGroup>
</Project>
......@@ -6,27 +6,23 @@
<DebugType>portable</DebugType>
<OutputType>Exe</OutputType>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<TargetFramework>netcoreapp1.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<DefineConstants>$(DefineConstants);COREFX;</DefineConstants>
<TargetFrameworks>netcoreapp1.0;netcoreapp2.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\Dapper.Tests\Helpers\Assert.cs;..\Dapper.Tests\Helpers\XunitSkippable.cs;..\Dapper\TypeExtensions.cs" />
<Compile Include="..\Dapper.Tests\Helpers\XunitSkippable.cs;..\Dapper\TypeExtensions.cs" />
<None Remove="Test.DB.sdf" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dapper\Dapper.csproj" />
<ProjectReference Include="..\Dapper.Contrib\Dapper.Contrib.csproj" />
<ProjectReference Include="..\Dapper.SqlBuilder\Dapper.SqlBuilder.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.3.0-beta1-build3642" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.0-beta1-build1309" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.0-beta1-build3642" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="Microsoft.Data.Sqlite" Version="1.1.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="1.1.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
<PackageReference Include="MySql.Data" Version="7.0.7-m61" />
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<PackageReference Include="xunit" Version="$(xUnitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(xUnitVersion)" />
<DotNetCliToolReference Include="dotnet-xunit" Version="$(xUnitVersion)" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
......
......@@ -5,6 +5,7 @@
using Dapper.Contrib.Extensions;
using FactAttribute = Dapper.Tests.Contrib.SkippableFactAttribute;
using Xunit;
namespace Dapper.Tests.Contrib
{
......@@ -23,32 +24,32 @@ public async Task InsertGetUpdateDeleteWithExplicitKeyAsync()
var originalxCount = (await connection.QueryAsync<int>("Select Count(*) From ObjectX").ConfigureAwait(false)).First();
await connection.InsertAsync(o1).ConfigureAwait(false);
var list1 = (await connection.QueryAsync<ObjectX>("select * from ObjectX").ConfigureAwait(false)).ToList();
list1.Count.IsEqualTo(originalxCount + 1);
Assert.Equal(list1.Count, originalxCount + 1);
o1 = await connection.GetAsync<ObjectX>(guid).ConfigureAwait(false);
o1.ObjectXId.IsEqualTo(guid);
Assert.Equal(o1.ObjectXId, guid);
o1.Name = "Bar";
await connection.UpdateAsync(o1).ConfigureAwait(false);
o1 = await connection.GetAsync<ObjectX>(guid).ConfigureAwait(false);
o1.Name.IsEqualTo("Bar");
Assert.Equal("Bar", o1.Name);
await connection.DeleteAsync(o1).ConfigureAwait(false);
o1 = await connection.GetAsync<ObjectX>(guid).ConfigureAwait(false);
o1.IsNull();
Assert.Null(o1);
const int id = 42;
var o2 = new ObjectY { ObjectYId = id, Name = "Foo" };
var originalyCount = connection.Query<int>("Select Count(*) From ObjectY").First();
await connection.InsertAsync(o2).ConfigureAwait(false);
var list2 = (await connection.QueryAsync<ObjectY>("select * from ObjectY").ConfigureAwait(false)).ToList();
list2.Count.IsEqualTo(originalyCount+1);
Assert.Equal(list2.Count, originalyCount+1);
o2 = await connection.GetAsync<ObjectY>(id).ConfigureAwait(false);
o2.ObjectYId.IsEqualTo(id);
Assert.Equal(o2.ObjectYId, id);
o2.Name = "Bar";
await connection.UpdateAsync(o2).ConfigureAwait(false);
o2 = await connection.GetAsync<ObjectY>(id).ConfigureAwait(false);
o2.Name.IsEqualTo("Bar");
Assert.Equal("Bar", o2.Name);
await connection.DeleteAsync(o2).ConfigureAwait(false);
o2 = await connection.GetAsync<ObjectY>(id).ConfigureAwait(false);
o2.IsNull();
Assert.Null(o2);
}
}
......@@ -60,12 +61,12 @@ public async Task TableNameAsync()
// tests against "Automobiles" table (Table attribute)
var id = await connection.InsertAsync(new Car { Name = "VolvoAsync" }).ConfigureAwait(false);
var car = await connection.GetAsync<Car>(id).ConfigureAwait(false);
car.IsNotNull();
car.Name.IsEqualTo("VolvoAsync");
(await connection.UpdateAsync(new Car { Id = id, Name = "SaabAsync" }).ConfigureAwait(false)).IsEqualTo(true);
(await connection.GetAsync<Car>(id).ConfigureAwait(false)).Name.IsEqualTo("SaabAsync");
(await connection.DeleteAsync(new Car { Id = id }).ConfigureAwait(false)).IsEqualTo(true);
(await connection.GetAsync<Car>(id).ConfigureAwait(false)).IsNull();
Assert.NotNull(car);
Assert.Equal("VolvoAsync", car.Name);
Assert.True(await connection.UpdateAsync(new Car { Id = id, Name = "SaabAsync" }).ConfigureAwait(false));
Assert.Equal("SaabAsync", (await connection.GetAsync<Car>(id).ConfigureAwait(false)).Name);
Assert.True(await connection.DeleteAsync(new Car { Id = id }).ConfigureAwait(false));
Assert.Null(await connection.GetAsync<Car>(id).ConfigureAwait(false));
}
}
......@@ -76,8 +77,8 @@ public async Task TestSimpleGetAsync()
{
var id = await connection.InsertAsync(new User { Name = "Adama", Age = 10 }).ConfigureAwait(false);
var user = await connection.GetAsync<User>(id).ConfigureAwait(false);
user.Id.IsEqualTo(id);
user.Name.IsEqualTo("Adama");
Assert.Equal(id, user.Id);
Assert.Equal("Adama", user.Name);
await connection.DeleteAsync(user).ConfigureAwait(false);
}
}
......@@ -87,7 +88,7 @@ public async Task InsertGetUpdateAsync()
{
using (var connection = GetOpenConnection())
{
(await connection.GetAsync<User>(30).ConfigureAwait(false)).IsNull();
Assert.Null(await connection.GetAsync<User>(30).ConfigureAwait(false));
var originalCount = (await connection.QueryAsync<int>("select Count(*) from Users").ConfigureAwait(false)).First();
......@@ -95,29 +96,29 @@ public async Task InsertGetUpdateAsync()
//get a user with "isdirty" tracking
var user = await connection.GetAsync<IUser>(id).ConfigureAwait(false);
user.Name.IsEqualTo("Adam");
(await connection.UpdateAsync(user).ConfigureAwait(false)).IsEqualTo(false); //returns false if not updated, based on tracking
Assert.Equal("Adam", user.Name);
Assert.False(await connection.UpdateAsync(user).ConfigureAwait(false)); //returns false if not updated, based on tracking
user.Name = "Bob";
(await connection.UpdateAsync(user).ConfigureAwait(false)).IsEqualTo(true); //returns true if updated, based on tracking
Assert.True(await connection.UpdateAsync(user).ConfigureAwait(false)); //returns true if updated, based on tracking
user = await connection.GetAsync<IUser>(id).ConfigureAwait(false);
user.Name.IsEqualTo("Bob");
Assert.Equal("Bob", user.Name);
//get a user with no tracking
var notrackedUser = await connection.GetAsync<User>(id).ConfigureAwait(false);
notrackedUser.Name.IsEqualTo("Bob");
(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)).IsEqualTo(true);
Assert.Equal("Bob", notrackedUser.Name);
Assert.True(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false));
//returns true, even though user was not changed
notrackedUser.Name = "Cecil";
(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)).IsEqualTo(true);
(await connection.GetAsync<User>(id).ConfigureAwait(false)).Name.IsEqualTo("Cecil");
Assert.True(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false));
Assert.Equal("Cecil", (await connection.GetAsync<User>(id).ConfigureAwait(false)).Name);
(await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count().IsEqualTo(originalCount+1);
(await connection.DeleteAsync(user).ConfigureAwait(false)).IsEqualTo(true);
(await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count().IsEqualTo(originalCount);
Assert.Equal((await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count(), originalCount+1);
Assert.True(await connection.DeleteAsync(user).ConfigureAwait(false));
Assert.Equal((await connection.QueryAsync<User>("select * from Users").ConfigureAwait(false)).Count(), originalCount);
(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)).IsEqualTo(false); //returns false, user not found
Assert.False(await connection.UpdateAsync(notrackedUser).ConfigureAwait(false)); //returns false, user not found
(await connection.InsertAsync(new User {Name = "Adam", Age = 10}).ConfigureAwait(false)).IsMoreThan(originalCount + 1);
Assert.True(await connection.InsertAsync(new User {Name = "Adam", Age = 10}).ConfigureAwait(false) > originalCount + 1);
}
}
......@@ -128,10 +129,10 @@ public async Task InsertCheckKeyAsync()
{
await connection.DeleteAllAsync<User>().ConfigureAwait(false);
(await connection.GetAsync<IUser>(3).ConfigureAwait(false)).IsNull();
Assert.Null(await connection.GetAsync<IUser>(3).ConfigureAwait(false));
var user = new User { Name = "Adamb", Age = 10 };
var id = await connection.InsertAsync(user).ConfigureAwait(false);
user.Id.IsEqualTo(id);
Assert.Equal(user.Id, id);
}
}
......@@ -215,9 +216,9 @@ private async Task InsertHelperAsync<T>(Func<IEnumerable<User>, T> helper)
await connection.DeleteAllAsync<User>().ConfigureAwait(false);
var total = await connection.InsertAsync(helper(users)).ConfigureAwait(false);
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
}
}
......@@ -247,16 +248,16 @@ private async Task UpdateHelperAsync<T>(Func<IEnumerable<User>, T> helper)
await connection.DeleteAllAsync<User>().ConfigureAwait(false);
var total = await connection.InsertAsync(helper(users)).ConfigureAwait(false);
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
foreach (var user in users)
{
user.Name += " updated";
}
await connection.UpdateAsync(helper(users)).ConfigureAwait(false);
var name = connection.Query<User>("select * from Users").First().Name;
name.Contains("updated").IsTrue();
Assert.Contains("updated", name);
}
}
......@@ -286,14 +287,14 @@ private async Task DeleteHelperAsync<T>(Func<IEnumerable<User>, T> helper)
await connection.DeleteAllAsync<User>().ConfigureAwait(false);
var total = await connection.InsertAsync(helper(users)).ConfigureAwait(false);
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
var usersToDelete = users.Take(10).ToList();
await connection.DeleteAsync(helper(usersToDelete)).ConfigureAwait(false);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities - 10);
Assert.Equal(users.Count, numberOfEntities - 10);
}
}
......@@ -311,11 +312,11 @@ public async Task GetAllAsync()
await connection.DeleteAllAsync<User>().ConfigureAwait(false);
var total = await connection.InsertAsync(users).ConfigureAwait(false);
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = (List<User>)await connection.GetAllAsync<User>().ConfigureAwait(false);
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
var iusers = await connection.GetAllAsync<IUser>().ConfigureAwait(false);
iusers.ToList().Count.IsEqualTo(numberOfEntities);
Assert.Equal(iusers.ToList().Count, numberOfEntities);
}
}
......@@ -328,7 +329,7 @@ public async Task InsertFieldWithReservedNameAsync()
var id = await connection.InsertAsync(new Result { Name = "Adam", Order = 1 }).ConfigureAwait(false);
var result = await connection.GetAsync<Result>(id).ConfigureAwait(false);
result.Order.IsEqualTo(1);
Assert.Equal(1, result.Order);
}
}
......@@ -342,8 +343,8 @@ public async Task DeleteAllAsync()
var id1 = await connection.InsertAsync(new User { Name = "Alice", Age = 32 }).ConfigureAwait(false);
var id2 = await connection.InsertAsync(new User { Name = "Bob", Age = 33 }).ConfigureAwait(false);
await connection.DeleteAllAsync<User>().ConfigureAwait(false);
(await connection.GetAsync<User>(id1).ConfigureAwait(false)).IsNull();
(await connection.GetAsync<User>(id2).ConfigureAwait(false)).IsNull();
Assert.Null(await connection.GetAsync<User>(id1).ConfigureAwait(false));
Assert.Null(await connection.GetAsync<User>(id2).ConfigureAwait(false));
}
}
}
......
......@@ -4,10 +4,11 @@
using System.Linq;
using Dapper.Contrib.Extensions;
using Xunit;
#if !COREFX
using System.Data.SqlServerCe;
#if !NETCOREAPP1_0 && !NETCOREAPP2_0
using System.Transactions;
using System.Data.SqlServerCe;
#endif
using FactAttribute = Dapper.Tests.Contrib.SkippableFactAttribute;
......@@ -110,7 +111,7 @@ public void Issue418()
Name = "Someone"
};
var updates = connection.Update(updateObject);
updates.IsFalse();
Assert.False(updates);
connection.DeleteAll<ObjectX>();
......@@ -122,7 +123,7 @@ public void Issue418()
};
connection.Insert(insertObject);
var list = connection.GetAll<ObjectX>();
list.Count().IsEqualTo(1);
Assert.Single(list);
}
}
......@@ -139,32 +140,32 @@ public void InsertGetUpdateDeleteWithExplicitKey()
var originalxCount = connection.Query<int>("Select Count(*) From ObjectX").First();
connection.Insert(o1);
var list1 = connection.Query<ObjectX>("select * from ObjectX").ToList();
list1.Count.IsEqualTo(originalxCount + 1);
Assert.Equal(list1.Count, originalxCount + 1);
o1 = connection.Get<ObjectX>(guid);
o1.ObjectXId.IsEqualTo(guid);
Assert.Equal(o1.ObjectXId, guid);
o1.Name = "Bar";
connection.Update(o1);
o1 = connection.Get<ObjectX>(guid);
o1.Name.IsEqualTo("Bar");
Assert.Equal("Bar", o1.Name);
connection.Delete(o1);
o1 = connection.Get<ObjectX>(guid);
o1.IsNull();
Assert.Null(o1);
const int id = 42;
var o2 = new ObjectY { ObjectYId = id, Name = "Foo" };
var originalyCount = connection.Query<int>("Select Count(*) From ObjectY").First();
connection.Insert(o2);
var list2 = connection.Query<ObjectY>("select * from ObjectY").ToList();
list2.Count.IsEqualTo(originalyCount + 1);
Assert.Equal(list2.Count, originalyCount + 1);
o2 = connection.Get<ObjectY>(id);
o2.ObjectYId.IsEqualTo(id);
Assert.Equal(o2.ObjectYId, id);
o2.Name = "Bar";
connection.Update(o2);
o2 = connection.Get<ObjectY>(id);
o2.Name.IsEqualTo("Bar");
Assert.Equal("Bar", o2.Name);
connection.Delete(o2);
o2 = connection.Get<ObjectY>(id);
o2.IsNull();
Assert.Null(o2);
}
}
......@@ -178,8 +179,8 @@ public void GetAllWithExplicitKey()
connection.Insert(o1);
var objectXs = connection.GetAll<ObjectX>().ToList();
objectXs.Count.IsMoreThan(0);
objectXs.Count(x => x.ObjectXId== guid).IsEqualTo(1);
Assert.True(objectXs.Count > 0);
Assert.Equal(1, objectXs.Count(x => x.ObjectXId== guid));
}
}
......@@ -192,16 +193,9 @@ public void InsertGetUpdateDeleteWithExplicitKeyNamedId()
var o2 = new ObjectZ { Id = id, Name = "Foo" };
connection.Insert(o2);
var list2 = connection.Query<ObjectZ>("select * from ObjectZ").ToList();
list2.Count.IsEqualTo(1);
Assert.Single(list2);
o2 = connection.Get<ObjectZ>(id);
o2.Id.IsEqualTo(id);
//o2.Name = "Bar";
//connection.Update(o2);
//o2 = connection.Get<ObjectY>(id);
//o2.Name.IsEqualTo("Bar");
//connection.Delete(o2);
//o2 = connection.Get<ObjectY>(id);
//o2.IsNull();
Assert.Equal(o2.Id, id);
}
}
......@@ -212,10 +206,10 @@ public void ShortIdentity()
{
const string name = "First item";
var id = connection.Insert(new Stuff { Name = name });
id.IsMoreThan(0); // 1-n are valid here, due to parallel tests
Assert.True(id > 0); // 1-n are valid here, due to parallel tests
var item = connection.Get<Stuff>(id);
item.TheId.IsEqualTo((short)id);
item.Name.IsEqualTo(name);
Assert.Equal(item.TheId, (short)id);
Assert.Equal(item.Name, name);
}
}
......@@ -227,8 +221,8 @@ public void NullDateTime()
connection.Insert(new Stuff { Name = "First item" });
connection.Insert(new Stuff { Name = "Second item", Created = DateTime.Now });
var stuff = connection.Query<Stuff>("select * from Stuff").ToList();
stuff[0].Created.IsNull();
stuff.Last().Created.IsNotNull();
Assert.Null(stuff[0].Created);
Assert.NotNull(stuff.Last().Created);
}
}
......@@ -240,13 +234,13 @@ public void TableName()
// tests against "Automobiles" table (Table attribute)
var id = connection.Insert(new Car { Name = "Volvo" });
var car = connection.Get<Car>(id);
car.IsNotNull();
car.Name.IsEqualTo("Volvo");
connection.Get<Car>(id).Name.IsEqualTo("Volvo");
connection.Update(new Car { Id = (int)id, Name = "Saab" }).IsEqualTo(true);
connection.Get<Car>(id).Name.IsEqualTo("Saab");
connection.Delete(new Car { Id = (int)id }).IsEqualTo(true);
connection.Get<Car>(id).IsNull();
Assert.NotNull(car);
Assert.Equal("Volvo", car.Name);
Assert.Equal("Volvo", connection.Get<Car>(id).Name);
Assert.True(connection.Update(new Car { Id = (int)id, Name = "Saab" }));
Assert.Equal("Saab", connection.Get<Car>(id).Name);
Assert.True(connection.Delete(new Car { Id = (int)id }));
Assert.Null(connection.Get<Car>(id));
}
}
......@@ -257,8 +251,8 @@ public void TestSimpleGet()
{
var id = connection.Insert(new User { Name = "Adama", Age = 10 });
var user = connection.Get<User>(id);
user.Id.IsEqualTo((int)id);
user.Name.IsEqualTo("Adama");
Assert.Equal(user.Id, (int)id);
Assert.Equal("Adama", user.Name);
connection.Delete(user);
}
}
......@@ -268,9 +262,9 @@ public void TestClosedConnection()
{
using (var connection = GetConnection())
{
connection.Insert(new User { Name = "Adama", Age = 10 }).IsMoreThan(0);
Assert.True(connection.Insert(new User { Name = "Adama", Age = 10 }) > 0);
var users = connection.GetAll<User>();
users.Count().IsMoreThan(0);
Assert.NotEmpty(users);
}
}
......@@ -300,9 +294,9 @@ private void InsertHelper<T>(Func<IEnumerable<User>, T> helper)
connection.DeleteAll<User>();
var total = connection.Insert(helper(users));
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
}
}
......@@ -332,16 +326,16 @@ private void UpdateHelper<T>(Func<IEnumerable<User>, T> helper)
connection.DeleteAll<User>();
var total = connection.Insert(helper(users));
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
foreach (var user in users)
{
user.Name += " updated";
}
connection.Update(helper(users));
var name = connection.Query<User>("select * from Users").First().Name;
name.Contains("updated").IsTrue();
Assert.Contains("updated", name);
}
}
......@@ -371,14 +365,14 @@ private void DeleteHelper<T>(Func<IEnumerable<User>, T> helper)
connection.DeleteAll<User>();
var total = connection.Insert(helper(users));
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
var usersToDelete = users.Take(10).ToList();
connection.Delete(helper(usersToDelete));
users = connection.Query<User>("select * from Users").ToList();
users.Count.IsEqualTo(numberOfEntities - 10);
Assert.Equal(users.Count, numberOfEntities - 10);
}
}
......@@ -388,7 +382,7 @@ public void InsertGetUpdate()
using (var connection = GetOpenConnection())
{
connection.DeleteAll<User>();
connection.Get<User>(3).IsNull();
Assert.Null(connection.Get<User>(3));
//insert with computed attribute that should be ignored
connection.Insert(new Car { Name = "Volvo", Computed = "this property should be ignored" });
......@@ -397,30 +391,30 @@ public void InsertGetUpdate()
//get a user with "isdirty" tracking
var user = connection.Get<IUser>(id);
user.Name.IsEqualTo("Adam");
connection.Update(user).IsEqualTo(false); //returns false if not updated, based on tracking
Assert.Equal("Adam", user.Name);
Assert.False(connection.Update(user)); //returns false if not updated, based on tracking
user.Name = "Bob";
connection.Update(user).IsEqualTo(true); //returns true if updated, based on tracking
Assert.True(connection.Update(user)); //returns true if updated, based on tracking
user = connection.Get<IUser>(id);
user.Name.IsEqualTo("Bob");
Assert.Equal("Bob", user.Name);
//get a user with no tracking
var notrackedUser = connection.Get<User>(id);
notrackedUser.Name.IsEqualTo("Bob");
connection.Update(notrackedUser).IsEqualTo(true); //returns true, even though user was not changed
Assert.Equal("Bob", notrackedUser.Name);
Assert.True(connection.Update(notrackedUser)); //returns true, even though user was not changed
notrackedUser.Name = "Cecil";
connection.Update(notrackedUser).IsEqualTo(true);
connection.Get<User>(id).Name.IsEqualTo("Cecil");
Assert.True(connection.Update(notrackedUser));
Assert.Equal("Cecil", connection.Get<User>(id).Name);
connection.Query<User>("select * from Users").Count().IsEqualTo(1);
connection.Delete(user).IsEqualTo(true);
connection.Query<User>("select * from Users").Count().IsEqualTo(0);
Assert.Single(connection.Query<User>("select * from Users"));
Assert.True(connection.Delete(user));
Assert.Empty(connection.Query<User>("select * from Users"));
connection.Update(notrackedUser).IsEqualTo(false); //returns false, user not found
Assert.False(connection.Update(notrackedUser)); //returns false, user not found
}
}
#if !COREFX
#if !NETCOREAPP1_0 && !NETCOREAPP2_0
[Fact(Skip = "Not parallel friendly - thinking about how to test this")]
public void InsertWithCustomDbType()
{
......@@ -430,7 +424,7 @@ public void InsertWithCustomDbType()
using (var connection = GetOpenConnection())
{
connection.DeleteAll<User>();
connection.Get<User>(3).IsNull();
Assert.IsNull(connection.Get<User>(3));
try
{
connection.Insert(new User { Name = "Adam", Age = 10 });
......@@ -477,7 +471,7 @@ public void InsertWithCustomTableNameMapper()
using (var connection = GetOpenConnection())
{
var id = connection.Insert(new Person { Name = "Mr Mapper" });
id.IsEqualTo(1);
Assert.Equal(1, id);
connection.GetAll<Person>();
}
}
......@@ -496,13 +490,13 @@ public void GetAll()
connection.DeleteAll<User>();
var total = connection.Insert(users);
total.IsEqualTo(numberOfEntities);
Assert.Equal(total, numberOfEntities);
users = connection.GetAll<User>().ToList();
users.Count.IsEqualTo(numberOfEntities);
Assert.Equal(users.Count, numberOfEntities);
var iusers = connection.GetAll<IUser>().ToList();
iusers.Count.IsEqualTo(numberOfEntities);
Assert.Equal(iusers.Count, numberOfEntities);
for (var i = 0; i < numberOfEntities; i++)
iusers[i].Age.IsEqualTo(i);
Assert.Equal(iusers[i].Age, i);
}
}
......@@ -521,11 +515,11 @@ public void Transactions()
tran.Rollback();
car = connection.Get<Car>(id); //updates should have been rolled back
car.Name.IsEqualTo(orgName);
Assert.Equal(car.Name, orgName);
}
}
#if !COREFX
#if !NETCOREAPP1_0 && !NETCOREAPP2_0
[Fact]
public void TransactionScope()
{
......@@ -537,7 +531,7 @@ public void TransactionScope()
txscope.Dispose(); //rollback
connection.Get<Car>(id).IsNull(); //returns null - car with that id should not exist
Assert.IsNull(connection.Get<Car>(id)); //returns null - car with that id should not exist
}
}
}
......@@ -548,10 +542,10 @@ public void InsertCheckKey()
{
using (var connection = GetOpenConnection())
{
connection.Get<IUser>(3).IsNull();
Assert.Null(connection.Get<IUser>(3));
User user = new User { Name = "Adamb", Age = 10 };
int id = (int)connection.Insert(user);
user.Id.IsEqualTo(id);
Assert.Equal(user.Id, id);
}
}
......@@ -614,7 +608,7 @@ public void InsertFieldWithReservedName()
var id = connection.Insert(new Result() { Name = "Adam", Order = 1 });
var result = connection.Get<Result>(id);
result.Order.IsEqualTo(1);
Assert.Equal(1, result.Order);
}
}
......@@ -625,11 +619,10 @@ public void DeleteAll()
{
var id1 = connection.Insert(new User { Name = "Alice", Age = 32 });
var id2 = connection.Insert(new User { Name = "Bob", Age = 33 });
connection.DeleteAll<User>().IsTrue();
connection.Get<User>(id1).IsNull();
connection.Get<User>(id2).IsNull();
Assert.True(connection.DeleteAll<User>());
Assert.Null(connection.Get<User>(id1));
Assert.Null(connection.Get<User>(id2));
}
}
}
}
using System;
using Microsoft.Data.Sqlite;
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using Xunit;
using Xunit.Sdk;
#if COREFX
using Microsoft.Data.Sqlite;
#else
using System.Data.SQLite;
#if !NETCOREAPP1_0 && !NETCOREAPP2_0
using System.Data.SqlServerCe;
using MySql.Data.MySqlClient;
using SqliteConnection = System.Data.SQLite.SQLiteConnection;
#endif
namespace Dapper.Tests.Contrib
......@@ -20,6 +18,7 @@ namespace Dapper.Tests.Contrib
// If we want to support a new provider, they need only be added here - not in multiple places
[XunitTestCaseDiscoverer("Dapper.Tests.SkippableFactDiscoverer", "Dapper.Tests.Contrib")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class SkippableFactAttribute : FactAttribute
{
}
......@@ -38,32 +37,31 @@ static SqlServerTestSuite()
using (var connection = new SqlConnection(ConnectionString))
{
// ReSharper disable once AccessToDisposedClosure
Action<string> dropTable = name => connection.Execute($@"IF OBJECT_ID('{name}', 'U') IS NOT NULL DROP TABLE [{name}]; ");
Action<string> dropTable = name => connection.Execute($"IF OBJECT_ID('{name}', 'U') IS NOT NULL DROP TABLE [{name}]; ");
connection.Open();
dropTable("Stuff");
connection.Execute(@"CREATE TABLE Stuff (TheId int IDENTITY(1,1) not null, Name nvarchar(100) not null, Created DateTime null);");
connection.Execute("CREATE TABLE Stuff (TheId int IDENTITY(1,1) not null, Name nvarchar(100) not null, Created DateTime null);");
dropTable("People");
connection.Execute(@"CREATE TABLE People (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE People (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null);");
dropTable("Users");
connection.Execute(@"CREATE TABLE Users (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, Age int not null);");
connection.Execute("CREATE TABLE Users (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, Age int not null);");
dropTable("Automobiles");
connection.Execute(@"CREATE TABLE Automobiles (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE Automobiles (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null);");
dropTable("Results");
connection.Execute(@"CREATE TABLE Results (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, [Order] int not null);");
connection.Execute("CREATE TABLE Results (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null, [Order] int not null);");
dropTable("ObjectX");
connection.Execute(@"CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null);");
dropTable("ObjectY");
connection.Execute(@"CREATE TABLE ObjectY (ObjectYId int not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE ObjectY (ObjectYId int not null, Name nvarchar(100) not null);");
dropTable("ObjectZ");
connection.Execute(@"CREATE TABLE ObjectZ (Id int not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE ObjectZ (Id int not null, Name nvarchar(100) not null);");
}
}
}
#if !COREFX
public class MySqlServerTestSuite : TestSuite
{
const string DbName = "DapperContribTests";
private const string DbName = "DapperContribTests";
public static string ConnectionString { get; private set; } =
IsAppVeyor
......@@ -85,25 +83,25 @@ static MySqlServerTestSuite()
using (var connection = new MySqlConnection(ConnectionString))
{
// ReSharper disable once AccessToDisposedClosure
Action<string> dropTable = name => connection.Execute($@"DROP TABLE IF EXISTS `{name}`;");
Action<string> dropTable = name => connection.Execute($"DROP TABLE IF EXISTS `{name}`;");
connection.Open();
connection.Execute($@"DROP DATABASE IF EXISTS {DbName}; CREATE DATABASE {DbName}; USE {DbName};");
connection.Execute($"DROP DATABASE IF EXISTS {DbName}; CREATE DATABASE {DbName}; USE {DbName};");
dropTable("Stuff");
connection.Execute(@"CREATE TABLE Stuff (TheId int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null, Created DateTime null);");
connection.Execute("CREATE TABLE Stuff (TheId int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null, Created DateTime null);");
dropTable("People");
connection.Execute(@"CREATE TABLE People (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE People (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null);");
dropTable("Users");
connection.Execute(@"CREATE TABLE Users (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null, Age int not null);");
connection.Execute("CREATE TABLE Users (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null, Age int not null);");
dropTable("Automobiles");
connection.Execute(@"CREATE TABLE Automobiles (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE Automobiles (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null);");
dropTable("Results");
connection.Execute(@"CREATE TABLE Results (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null, `Order` int not null);");
connection.Execute("CREATE TABLE Results (Id int not null AUTO_INCREMENT PRIMARY KEY, Name nvarchar(100) not null, `Order` int not null);");
dropTable("ObjectX");
connection.Execute(@"CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null);");
dropTable("ObjectY");
connection.Execute(@"CREATE TABLE ObjectY (ObjectYId int not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE ObjectY (ObjectYId int not null, Name nvarchar(100) not null);");
dropTable("ObjectZ");
connection.Execute(@"CREATE TABLE ObjectZ (Id int not null, Name nvarchar(100) not null);");
connection.Execute("CREATE TABLE ObjectZ (Id int not null, Name nvarchar(100) not null);");
}
}
catch (MySqlException e)
......@@ -116,13 +114,10 @@ static MySqlServerTestSuite()
}
}
// This doesn't work on COREFX right now due to:
// In Visual Studio: Interop loads (works from console, though)
// In general: parameter names, see https://github.com/StackExchange/dapper-dot-net/issues/375
public class SQLiteTestSuite : TestSuite
{
const string FileName = "Test.DB.sqlite";
public static string ConnectionString => $"Filename={FileName};";
private const string FileName = "Test.DB.sqlite";
public static string ConnectionString => $"Filename=./{FileName};Mode=ReadWriteCreate;";
public override IDbConnection GetConnection() => new SqliteConnection(ConnectionString);
static SQLiteTestSuite()
......@@ -131,22 +126,22 @@ static SQLiteTestSuite()
{
File.Delete(FileName);
}
SqliteConnection.CreateFile(FileName);
using (var connection = new SqliteConnection(ConnectionString))
{
connection.Open();
connection.Execute(@"CREATE TABLE Stuff (TheId integer primary key autoincrement not null, Name nvarchar(100) not null, Created DateTime null) ");
connection.Execute(@"CREATE TABLE People (Id integer primary key autoincrement not null, Name nvarchar(100) not null) ");
connection.Execute(@"CREATE TABLE Users (Id integer primary key autoincrement not null, Name nvarchar(100) not null, Age int not null) ");
connection.Execute(@"CREATE TABLE Automobiles (Id integer primary key autoincrement not null, Name nvarchar(100) not null) ");
connection.Execute(@"CREATE TABLE Results (Id integer primary key autoincrement not null, Name nvarchar(100) not null, [Order] int not null) ");
connection.Execute(@"CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null) ");
connection.Execute(@"CREATE TABLE ObjectY (ObjectYId integer not null, Name nvarchar(100) not null) ");
connection.Execute(@"CREATE TABLE ObjectZ (Id integer not null, Name nvarchar(100) not null) ");
connection.Execute("CREATE TABLE Stuff (TheId integer primary key autoincrement not null, Name nvarchar(100) not null, Created DateTime null) ");
connection.Execute("CREATE TABLE People (Id integer primary key autoincrement not null, Name nvarchar(100) not null) ");
connection.Execute("CREATE TABLE Users (Id integer primary key autoincrement not null, Name nvarchar(100) not null, Age int not null) ");
connection.Execute("CREATE TABLE Automobiles (Id integer primary key autoincrement not null, Name nvarchar(100) not null) ");
connection.Execute("CREATE TABLE Results (Id integer primary key autoincrement not null, Name nvarchar(100) not null, [Order] int not null) ");
connection.Execute("CREATE TABLE ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null) ");
connection.Execute("CREATE TABLE ObjectY (ObjectYId integer not null, Name nvarchar(100) not null) ");
connection.Execute("CREATE TABLE ObjectZ (Id integer not null, Name nvarchar(100) not null) ");
}
}
}
#if !NETCOREAPP1_0 && !NETCOREAPP2_0
public class SqlCETestSuite : TestSuite
{
const string FileName = "Test.DB.sdf";
......
......@@ -8,7 +8,7 @@ public class BelgradeBenchmarks : BenchmarkBase
{
private QueryMapper _mapper;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -6,7 +6,7 @@ namespace Dapper.Tests.Performance
{
public class DapperBenchmarks : BenchmarkBase
{
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -7,7 +7,7 @@ public class EF6Benchmarks : BenchmarkBase
{
private EntityFramework.EFContext Context;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -13,7 +13,7 @@ public class EFCoreBenchmarks : BenchmarkBase
private static readonly Func<DataClassesDataContext, int, Linq2Sql.Post> compiledQuery =
CompiledQuery.Compile((DataClassesDataContext ctx, int id) => ctx.Posts.First(p => p.Id == id));
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -9,11 +9,11 @@ public class HandCodedBenchmarks : BenchmarkBase
{
private SqlCommand _postCommand;
private SqlParameter _idParam;
#if !COREFX
#if !NETCOREAPP1_0
private DataTable _table;
#endif
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......@@ -24,7 +24,7 @@ public void Setup()
Counter1,Counter2,Counter3,Counter4,Counter5,Counter6,Counter7,Counter8,Counter9 from Posts where Id = @Id"
};
_idParam = _postCommand.Parameters.Add("@Id", SqlDbType.Int);
#if !COREFX
#if !NETCOREAPP1_0
_table = new DataTable
{
Columns =
......
......@@ -12,7 +12,7 @@ public class Linq2SqlBenchmarks : BenchmarkBase
private static readonly Func<DataClassesDataContext, int, Linq2Sql.Post> compiledQuery =
CompiledQuery.Compile((DataClassesDataContext ctx, int id) => ctx.Posts.First(p => p.Id == id));
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -8,7 +8,7 @@ public class MassiveBenchmarks : BenchmarkBase
{
private DynamicModel _model;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -13,7 +13,7 @@ public class NHibernateBenchmarks : BenchmarkBase
{
private IStatelessSession _sql, _hql, _criteria, _linq, _get;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -8,7 +8,7 @@ public class PetaPocoBenchmarks : BenchmarkBase
{
private Database _db, _dbFast;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -8,7 +8,7 @@ public class ServiceStackBenchmarks : BenchmarkBase
{
private IDbConnection _db;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -6,7 +6,7 @@ public class SomaBenchmarks : BenchmarkBase
{
private dynamic _sdb;
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -18,7 +18,7 @@ public class SusanooBenchmarks : BenchmarkBase
.DefineResults<dynamic>()
.Realize();
[Setup]
[GlobalSetup]
public void Setup()
{
BaseSetup();
......
......@@ -12,25 +12,27 @@
<ProjectReference Include="..\Dapper.Contrib\Dapper.Contrib.csproj" />
<ProjectReference Include="..\Dapper.EntityFramework\Dapper.EntityFramework.csproj" />
<PackageReference Include="Belgrade.Sql.Client" Version="0.7.0" />
<PackageReference Include="BenchmarkDotNet" Version="0.10.5" />
<PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="0.10.5" />
<PackageReference Include="BenchmarkDotNet" Version="0.10.9" />
<PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="0.10.9" />
<!--<PackageReference Include="BLToolkit" Version="4.3.6" />-->
<PackageReference Include="EntityFramework" Version="6.1.3" />
<PackageReference Include="FirebirdSql.Data.FirebirdClient" Version="5.9.0.1" />
<PackageReference Include="FirebirdSql.Data.FirebirdClient" Version="5.9.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
<PackageReference Include="Microsoft.SqlServer.Compact" Version="4.0.8876.1" />
<PackageReference Include="Microsoft.SqlServer.Types" Version="14.0.314.76" />
<PackageReference Include="MySql.Data" Version="7.0.7-m61" />
<PackageReference Include="NHibernate" Version="4.1.1.4000" />
<PackageReference Include="Npgsql" Version="3.2.2" />
<PackageReference Include="PetaPoco" Version="5.1.244" />
<PackageReference Include="ServiceStack.OrmLite.SqlServer.Signed" Version="4.5.8" />
<PackageReference Include="Iesi.Collections" Version="4.0.2" />
<PackageReference Include="Npgsql" Version="3.2.5" />
<PackageReference Include="PetaPoco" Version="5.1.259" />
<PackageReference Include="ServiceStack.OrmLite.SqlServer.Signed" Version="4.5.12" />
<PackageReference Include="Simple.Data.SqlServer" Version="2.0.0-alpha1" />
<PackageReference Include="Soma" Version="1.9.0.1" />
<PackageReference Include="SubSonic" Version="3.0.0.4" />
<PackageReference Include="Susanoo.SqlServer" Version="1.2.4.2" />
<PackageReference Include="System.Data.SQLite" Version="1.0.105" />
<PackageReference Include="System.Data.SQLite" Version="1.0.105.2" />
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq" />
......
......@@ -8,7 +8,7 @@ public class ORMColum : IColumn
{
public string Id => nameof(ORMColum);
public string ColumnName { get; } = "ORM";
public string Legend => "The object relational mapper being tested";
public string Legend => "The object/relational mapper being tested";
public bool IsDefault(Summary summary, Benchmark benchmark) => false;
public string GetValue(Summary summary, Benchmark benchmark) => benchmark.Target.Method.DeclaringType.Name.Replace("Benchmarks", string.Empty);
......
......@@ -341,7 +341,7 @@ public async Task RunAsync(int iterations)
}
}, "Hand Coded");
#if !COREFX
#if !NETSTANDARD1_3
var table = new DataTable
{
Columns =
......
#if !COREFX
#if !NETSTANDARD1_3
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
......
#if !COREFX
#if !NETSTANDARD1_3
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
......
#if !COREFX
#if !NETSTANDARD1_3
using System;
using System.Collections.Generic;
using System.Linq;
......
......@@ -19,35 +19,63 @@ public async Task TestBasicStringUsageAsync()
{
var query = await connection.QueryAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false);
var arr = query.ToArray();
arr.IsSequenceEqualTo(new[] { "abc", "def" });
Assert.Equal(new[] { "abc", "def" }, arr);
}
[Fact]
public async Task TestBasicStringUsageQueryFirstAsync()
{
var str = await connection.QueryFirstAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new {txt = "def"})).ConfigureAwait(false);
str.IsEqualTo("abc");
Assert.Equal("abc", str);
}
[Fact]
public async Task TestBasicStringUsageQueryFirstAsyncDynamic()
{
var str = await connection.QueryFirstAsync("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false);
Assert.Equal("abc", str.Value);
}
[Fact]
public async Task TestBasicStringUsageQueryFirstOrDefaultAsync()
{
var str = await connection.QueryFirstOrDefaultAsync<string>(new CommandDefinition("select null as [Value] union all select @txt", new {txt = "def"})).ConfigureAwait(false);
str.IsNull();
Assert.Null(str);
}
[Fact]
public async Task TestBasicStringUsageQuerySingleAsync()
public async Task TestBasicStringUsageQueryFirstOrDefaultAsyncDynamic()
{
var str = await connection.QueryFirstOrDefaultAsync("select null as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false);
Assert.Null(str.Value);
}
[Fact]
public async Task TestBasicStringUsageQuerySingleAsyncDynamic()
{
var str = await connection.QuerySingleAsync<string>(new CommandDefinition("select 'abc' as [Value]")).ConfigureAwait(false);
str.IsEqualTo("abc");
Assert.Equal("abc", str);
}
[Fact]
public async Task TestBasicStringUsageQuerySingleAsync()
{
var str = await connection.QuerySingleAsync("select 'abc' as [Value]").ConfigureAwait(false);
Assert.Equal("abc", str.Value);
}
[Fact]
public async Task TestBasicStringUsageQuerySingleOrDefaultAsync()
{
var str = await connection.QuerySingleAsync<string>(new CommandDefinition("select null as [Value]")).ConfigureAwait(false);
str.IsNull();
var str = await connection.QuerySingleOrDefaultAsync<string>(new CommandDefinition("select null as [Value]")).ConfigureAwait(false);
Assert.Null(str);
}
[Fact]
public async Task TestBasicStringUsageQuerySingleOrDefaultAsyncDynamic()
{
var str = await connection.QuerySingleOrDefaultAsync("select null as [Value]").ConfigureAwait(false);
Assert.Null(str.Value);
}
[Fact]
......@@ -55,7 +83,7 @@ public async Task TestBasicStringUsageAsyncNonBuffered()
{
var query = await connection.QueryAsync<string>(new CommandDefinition("select 'abc' as [Value] union all select @txt", new { txt = "def" }, flags: CommandFlags.None)).ConfigureAwait(false);
var arr = query.ToArray();
arr.IsSequenceEqualTo(new[] { "abc", "def" });
Assert.Equal(new[] { "abc", "def" }, arr);
}
[Fact]
......@@ -72,7 +100,7 @@ public void TestLongOperationWithCancellation()
}
catch (AggregateException agg)
{
(agg.InnerException is SqlException).IsTrue();
Assert.True(agg.InnerException is SqlException);
}
}
......@@ -81,7 +109,7 @@ public async Task TestBasicStringUsageClosedAsync()
{
var query = await connection.QueryAsync<string>("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false);
var arr = query.ToArray();
arr.IsSequenceEqualTo(new[] { "abc", "def" });
Assert.Equal(new[] { "abc", "def" }, arr);
}
[Fact]
......@@ -89,7 +117,7 @@ public async Task TestQueryDynamicAsync()
{
var row = (await connection.QueryAsync("select 'abc' as [Value]").ConfigureAwait(false)).Single();
string value = row.Value;
value.IsEqualTo("abc");
Assert.Equal("abc", value);
}
[Fact]
......@@ -97,7 +125,7 @@ public async Task TestClassWithStringUsageAsync()
{
var query = await connection.QueryAsync<BasicType>("select 'abc' as [Value] union all select @txt", new { txt = "def" }).ConfigureAwait(false);
var arr = query.ToArray();
arr.Select(x => x.Value).IsSequenceEqualTo(new[] { "abc", "def" });
Assert.Equal(new[] { "abc", "def" }, arr.Select(x => x.Value));
}
[Fact]
......@@ -118,7 +146,7 @@ public void TestExecuteClosedConnAsyncInner()
[Fact]
public async Task TestMultiMapWithSplitAsync()
{
const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name";
const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name";
var productQuery = await connection.QueryAsync<Product, Category, Product>(sql, (prod, cat) =>
{
prod.Category = cat;
......@@ -127,16 +155,16 @@ public async Task TestMultiMapWithSplitAsync()
var product = productQuery.First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.Id.IsEqualTo(2);
product.Category.Name.IsEqualTo("def");
Assert.Equal(1, product.Id);
Assert.Equal("abc", product.Name);
Assert.Equal(2, product.Category.Id);
Assert.Equal("def", product.Category.Name);
}
[Fact]
public async Task TestMultiMapArbitraryWithSplitAsync()
{
const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name";
const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name";
var productQuery = await connection.QueryAsync<Product>(sql, new[] { typeof(Product), typeof(Category) }, (objects) => {
var prod = (Product)objects[0];
prod.Category = (Category)objects[1];
......@@ -145,16 +173,16 @@ public async Task TestMultiMapArbitraryWithSplitAsync()
var product = productQuery.First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.Id.IsEqualTo(2);
product.Category.Name.IsEqualTo("def");
Assert.Equal(1, product.Id);
Assert.Equal("abc", product.Name);
Assert.Equal(2, product.Category.Id);
Assert.Equal("def", product.Category.Name);
}
[Fact]
public async Task TestMultiMapWithSplitClosedConnAsync()
{
const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name";
const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name";
using (var conn = GetClosedConnection())
{
var productQuery = await conn.QueryAsync<Product, Category, Product>(sql, (prod, cat) =>
......@@ -165,10 +193,10 @@ public async Task TestMultiMapWithSplitClosedConnAsync()
var product = productQuery.First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.Id.IsEqualTo(2);
product.Category.Name.IsEqualTo("def");
Assert.Equal(1, product.Id);
Assert.Equal("abc", product.Name);
Assert.Equal(2, product.Category.Id);
Assert.Equal("def", product.Category.Name);
}
}
......@@ -177,8 +205,8 @@ public async Task TestMultiAsync()
{
using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2").ConfigureAwait(false))
{
multi.ReadAsync<int>().Result.Single().IsEqualTo(1);
multi.ReadAsync<int>().Result.Single().IsEqualTo(2);
Assert.Equal(1, multi.ReadAsync<int>().Result.Single());
Assert.Equal(2, multi.ReadAsync<int>().Result.Single());
}
}
......@@ -187,11 +215,11 @@ public async Task TestMultiAsyncViaFirstOrDefault()
{
using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2; select 3; select 4; select 5").ConfigureAwait(false))
{
multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(1);
multi.ReadAsync<int>().Result.Single().IsEqualTo(2);
multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(3);
multi.ReadAsync<int>().Result.Single().IsEqualTo(4);
multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(5);
Assert.Equal(1, multi.ReadFirstOrDefaultAsync<int>().Result);
Assert.Equal(2, multi.ReadAsync<int>().Result.Single());
Assert.Equal(3, multi.ReadFirstOrDefaultAsync<int>().Result);
Assert.Equal(4, multi.ReadAsync<int>().Result.Single());
Assert.Equal(5, multi.ReadFirstOrDefaultAsync<int>().Result);
}
}
......@@ -200,8 +228,8 @@ public async Task TestMultiClosedConnAsync()
{
using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2").ConfigureAwait(false))
{
multi.ReadAsync<int>().Result.Single().IsEqualTo(1);
multi.ReadAsync<int>().Result.Single().IsEqualTo(2);
Assert.Equal(1, multi.ReadAsync<int>().Result.Single());
Assert.Equal(2, multi.ReadAsync<int>().Result.Single());
}
}
......@@ -210,26 +238,26 @@ public async Task TestMultiClosedConnAsyncViaFirstOrDefault()
{
using (SqlMapper.GridReader multi = await connection.QueryMultipleAsync("select 1; select 2; select 3; select 4; select 5;").ConfigureAwait(false))
{
multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(1);
multi.ReadAsync<int>().Result.Single().IsEqualTo(2);
multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(3);
multi.ReadAsync<int>().Result.Single().IsEqualTo(4);
multi.ReadFirstOrDefaultAsync<int>().Result.IsEqualTo(5);
Assert.Equal(1, multi.ReadFirstOrDefaultAsync<int>().Result);
Assert.Equal(2, multi.ReadAsync<int>().Result.Single());
Assert.Equal(3, multi.ReadFirstOrDefaultAsync<int>().Result);
Assert.Equal(4, multi.ReadAsync<int>().Result.Single());
Assert.Equal(5, multi.ReadFirstOrDefaultAsync<int>().Result);
}
}
#if !COREFX
#if !NETCOREAPP1_0
[Fact]
public async Task ExecuteReaderOpenAsync()
{
var dt = new DataTable();
dt.Load(await connection.ExecuteReaderAsync("select 3 as [three], 4 as [four]").ConfigureAwait(false));
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);
Assert.Equal(2, dt.Columns.Count);
Assert.Equal("three", dt.Columns[0].ColumnName);
Assert.Equal("four", dt.Columns[1].ColumnName);
Assert.Equal(1, dt.Rows.Count);
Assert.Equal(3, (int)dt.Rows[0][0]);
Assert.Equal(4, (int)dt.Rows[0][1]);
}
[Fact]
......@@ -239,12 +267,12 @@ public async Task ExecuteReaderClosedAsync()
{
var dt = new DataTable();
dt.Load(await conn.ExecuteReaderAsync("select 3 as [three], 4 as [four]").ConfigureAwait(false));
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);
Assert.Equal(2, dt.Columns.Count);
Assert.Equal("three", dt.Columns[0].ColumnName);
Assert.Equal("four", dt.Columns[1].ColumnName);
Assert.Equal(1, dt.Rows.Count);
Assert.Equal(3, (int)dt.Rows[0][0]);
Assert.Equal(4, (int)dt.Rows[0][1]);
}
}
#endif
......@@ -273,9 +301,9 @@ private async Task LiteralReplacement(IDbConnection conn)
var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } };
await conn.ExecuteAsync("insert literal1 (id,foo) values ({=id}, @foo)", rows).ConfigureAwait(false);
var count = (await conn.QueryAsync<int>("select count(1) from literal1 where id={=foo}", new { foo = 123 }).ConfigureAwait(false)).Single();
count.IsEqualTo(1);
Assert.Equal(1, count);
int sum = (await conn.QueryAsync<int>("select sum(id) + sum(foo) from literal1").ConfigureAwait(false)).Single();
sum.IsEqualTo(123 + 456 + 1 + 2 + 3 + 4);
Assert.Equal(sum, 123 + 456 + 1 + 2 + 3 + 4);
}
[Fact]
......@@ -302,7 +330,7 @@ private async Task LiteralReplacementDynamic(IDbConnection conn)
args = new DynamicParameters();
args.Add("foo", 123);
var count = (await conn.QueryAsync<int>("select count(1) from literal2 where id={=foo}", args).ConfigureAwait(false)).Single();
count.IsEqualTo(1);
Assert.Equal(1, count);
}
[Fact]
......@@ -316,10 +344,10 @@ public async Task LiteralInAsync()
}).ConfigureAwait(false);
var count = (await connection.QueryAsync<int>("select count(1) from #literalin where id in {=ids}",
new { ids = new[] { 1, 3, 4 } }).ConfigureAwait(false)).Single();
count.IsEqualTo(2);
Assert.Equal(2, count);
}
[Fact]
[FactLongRunning]
public async Task RunSequentialVersusParallelAsync()
{
var ids = Enumerable.Range(1, 20000).Select(id => new { id }).ToArray();
......@@ -336,7 +364,7 @@ public async Task RunSequentialVersusParallelAsync()
Console.WriteLine("Pipeline: {0}ms", watch.ElapsedMilliseconds);
}
[Fact]
[FactLongRunning]
public void RunSequentialVersusParallelSync()
{
var ids = Enumerable.Range(1, 20000).Select(id => new { id }).ToArray();
......@@ -353,11 +381,17 @@ public void RunSequentialVersusParallelSync()
Console.WriteLine("Pipeline: {0}ms", watch.ElapsedMilliseconds);
}
[Collection(NonParallelDefinition.Name)]
public class AsyncQueryCacheTests : TestBase
{
private SqlConnection _marsConnection;
private SqlConnection MarsConnection => _marsConnection ?? (_marsConnection = GetOpenConnection(true));
[Fact]
public void AssertNoCacheWorksForQueryMultiple()
{
const int a = 123, b = 456;
var cmdDef = new CommandDefinition(@"select @a; select @b;", new
var cmdDef = new CommandDefinition("select @a; select @b;", new
{
a, b
}, commandType: CommandType.Text, flags: CommandFlags.NoCache);
......@@ -371,10 +405,11 @@ public void AssertNoCacheWorksForQueryMultiple()
d = multi.Read<int>().Single();
}
int after = SqlMapper.GetCachedSQLCount();
before.IsEqualTo(0);
after.IsEqualTo(0);
c.IsEqualTo(123);
d.IsEqualTo(456);
Assert.Equal(0, before);
Assert.Equal(0, after);
Assert.Equal(123, c);
Assert.Equal(456, d);
}
}
private class BasicType
......@@ -388,11 +423,11 @@ public async Task TypeBasedViaTypeAsync()
Type type = Common.GetSomeType();
dynamic actual = (await MarsConnection.QueryAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).ConfigureAwait(false)).FirstOrDefault();
((object)actual).GetType().IsEqualTo(type);
Assert.Equal(((object)actual).GetType(), type);
int a = actual.A;
string b = actual.B;
a.IsEqualTo(123);
b.IsEqualTo("abc");
Assert.Equal(123, a);
Assert.Equal("abc", b);
}
[Fact]
......@@ -401,37 +436,37 @@ public async Task TypeBasedViaTypeAsyncFirstOrDefault()
Type type = Common.GetSomeType();
dynamic actual = await MarsConnection.QueryFirstOrDefaultAsync(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).ConfigureAwait(false);
((object)actual).GetType().IsEqualTo(type);
Assert.Equal(((object)actual).GetType(), type);
int a = actual.A;
string b = actual.B;
a.IsEqualTo(123);
b.IsEqualTo("abc");
Assert.Equal(123, a);
Assert.Equal("abc", b);
}
[Fact]
public async Task Issue22_ExecuteScalarAsync()
{
int i = await connection.ExecuteScalarAsync<int>("select 123").ConfigureAwait(false);
i.IsEqualTo(123);
Assert.Equal(123, i);
i = await connection.ExecuteScalarAsync<int>("select cast(123 as bigint)").ConfigureAwait(false);
i.IsEqualTo(123);
Assert.Equal(123, i);
long j = await connection.ExecuteScalarAsync<long>("select 123").ConfigureAwait(false);
j.IsEqualTo(123L);
Assert.Equal(123L, j);
j = await connection.ExecuteScalarAsync<long>("select cast(123 as bigint)").ConfigureAwait(false);
j.IsEqualTo(123L);
Assert.Equal(123L, j);
int? k = await connection.ExecuteScalarAsync<int?>("select @i", new { i = default(int?) }).ConfigureAwait(false);
k.IsNull();
Assert.Null(k);
}
[Fact]
public async Task Issue346_QueryAsyncConvert()
{
int i = (await connection.QueryAsync<int>("Select Cast(123 as bigint)").ConfigureAwait(false)).First();
i.IsEqualTo(123);
Assert.Equal(123, i);
}
[Fact]
......@@ -454,11 +489,11 @@ public async Task TestSupportForDynamicParametersOutputExpressionsAsync()
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId", p).ConfigureAwait(false);
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
}
}
......@@ -482,12 +517,12 @@ public async Task TestSupportForDynamicParametersOutputExpressions_ScalarAsync()
SET @AddressPersonId = @PersonId
select 42", p).ConfigureAwait(false));
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
......@@ -510,12 +545,12 @@ public async Task TestSupportForDynamicParametersOutputExpressions_Query_Default
SET @AddressPersonId = @PersonId
select 42", p).ConfigureAwait(false)).Single();
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
......@@ -538,12 +573,12 @@ public async Task TestSupportForDynamicParametersOutputExpressions_Query_Buffere
SET @AddressPersonId = @PersonId
select 42", p, flags: CommandFlags.Buffered)).ConfigureAwait(false)).Single();
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
......@@ -566,12 +601,12 @@ public async Task TestSupportForDynamicParametersOutputExpressions_Query_NonBuff
SET @AddressPersonId = @PersonId
select 42", p, flags: CommandFlags.None)).ConfigureAwait(false)).Single();
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
[Fact]
......@@ -600,35 +635,35 @@ select 17
y = multi.ReadAsync<int>().Result.Single();
}
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
x.IsEqualTo(42);
y.IsEqualTo(17);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, x);
Assert.Equal(17, y);
}
[Fact]
public async Task TestSubsequentQueriesSuccessAsync()
{
var data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0").ConfigureAwait(false)).ToList();
data0.Count.IsEqualTo(0);
Assert.Empty(data0);
var data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ConfigureAwait(false)).ToList();
data1.Count.IsEqualTo(0);
Assert.Empty(data1);
var data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ConfigureAwait(false)).ToList();
data2.Count.IsEqualTo(0);
Assert.Empty(data2);
data0 = (await connection.QueryAsync<AsyncFoo0>("select 1 as [Id] where 1 = 0").ConfigureAwait(false)).ToList();
data0.Count.IsEqualTo(0);
Assert.Empty(data0);
data1 = (await connection.QueryAsync<AsyncFoo1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ConfigureAwait(false)).ToList();
data1.Count.IsEqualTo(0);
Assert.Empty(data1);
data2 = (await connection.QueryAsync<AsyncFoo2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ConfigureAwait(false)).ToList();
data2.Count.IsEqualTo(0);
Assert.Empty(data2);
}
private class AsyncFoo0 { public int Id { get; set; } }
......@@ -644,12 +679,12 @@ public async Task TestSchemaChangedViaFirstOrDefaultAsync()
try
{
var d = await connection.QueryFirstOrDefaultAsync<Dog>("select * from #dog").ConfigureAwait(false);
d.Name.IsEqualTo("Alf");
d.Age.IsEqualTo(1);
Assert.Equal("Alf", d.Name);
Assert.Equal(1, d.Age);
connection.Execute("alter table #dog drop column Name");
d = await connection.QueryFirstOrDefaultAsync<Dog>("select * from #dog").ConfigureAwait(false);
d.Name.IsNull();
d.Age.IsEqualTo(1);
Assert.Null(d.Name);
Assert.Equal(1, d.Age);
}
finally
{
......@@ -716,26 +751,26 @@ public async Task TestMultiMapArbitraryMapsAsync()
var data = (await connection.QueryAsync<ReviewBoard>(sql, types, mapper).ConfigureAwait(false)).ToList();
var p = data[0];
p.Id.IsEqualTo(1);
p.Name.IsEqualTo("Review Board 1");
p.User1.Id.IsEqualTo(1);
p.User2.Id.IsEqualTo(2);
p.User3.Id.IsEqualTo(3);
p.User4.Id.IsEqualTo(4);
p.User5.Id.IsEqualTo(5);
p.User6.Id.IsEqualTo(6);
p.User7.Id.IsEqualTo(7);
p.User8.Id.IsEqualTo(8);
p.User9.Id.IsEqualTo(9);
p.User1.Name.IsEqualTo("User 1");
p.User2.Name.IsEqualTo("User 2");
p.User3.Name.IsEqualTo("User 3");
p.User4.Name.IsEqualTo("User 4");
p.User5.Name.IsEqualTo("User 5");
p.User6.Name.IsEqualTo("User 6");
p.User7.Name.IsEqualTo("User 7");
p.User8.Name.IsEqualTo("User 8");
p.User9.Name.IsEqualTo("User 9");
Assert.Equal(1, p.Id);
Assert.Equal("Review Board 1", p.Name);
Assert.Equal(1, p.User1.Id);
Assert.Equal(2, p.User2.Id);
Assert.Equal(3, p.User3.Id);
Assert.Equal(4, p.User4.Id);
Assert.Equal(5, p.User5.Id);
Assert.Equal(6, p.User6.Id);
Assert.Equal(7, p.User7.Id);
Assert.Equal(8, p.User8.Id);
Assert.Equal(9, p.User9.Id);
Assert.Equal("User 1", p.User1.Name);
Assert.Equal("User 2", p.User2.Name);
Assert.Equal("User 3", p.User3.Name);
Assert.Equal("User 4", p.User4.Name);
Assert.Equal("User 5", p.User5.Name);
Assert.Equal("User 6", p.User6.Name);
Assert.Equal("User 7", p.User7.Name);
Assert.Equal("User 8", p.User8.Name);
Assert.Equal("User 9", p.User9.Name);
}
finally
{
......@@ -747,16 +782,15 @@ public async Task TestMultiMapArbitraryMapsAsync()
public async Task Issue157_ClosedReaderAsync()
{
var args = new { x = 42 };
const string sql = @"select 123 as [A], 'abc' as [B] where @x=42";
const string sql = "select 123 as [A], 'abc' as [B] where @x=42";
var row = (await connection.QueryAsync<SomeType>(new CommandDefinition(
sql, args, flags:CommandFlags.None)).ConfigureAwait(false)).Single();
row.IsNotNull();
row.A.IsEqualTo(123);
row.B.IsEqualTo("abc");
Assert.NotNull(row);
Assert.Equal(123, row.A);
Assert.Equal("abc", row.B);
args = new { x = 5 };
(await connection.QueryAsync<SomeType>(new CommandDefinition(
sql, args, flags: CommandFlags.None)).ConfigureAwait(false)).Any().IsFalse();
Assert.False((await connection.QueryAsync<SomeType>(new CommandDefinition(sql, args, flags: CommandFlags.None)).ConfigureAwait(false)).Any());
}
[Fact]
......@@ -767,7 +801,7 @@ public async Task TestAtEscaping()
select @@Name = @Id+1
select @@Name
", new Product { Id = 1 }).ConfigureAwait(false)).Single();
id.IsEqualTo(2);
Assert.Equal(2, id);
}
[Fact]
......@@ -775,11 +809,11 @@ public async Task Issue1281_DataReaderOutOfOrderAsync()
{
using (var reader = await connection.ExecuteReaderAsync("Select 0, 1, 2").ConfigureAwait(false))
{
reader.Read().IsTrue();
reader.GetInt32(2).IsEqualTo(2);
reader.GetInt32(0).IsEqualTo(0);
reader.GetInt32(1).IsEqualTo(1);
reader.Read().IsFalse();
Assert.True(reader.Read());
Assert.Equal(2, reader.GetInt32(2));
Assert.Equal(0, reader.GetInt32(0));
Assert.Equal(1, reader.GetInt32(1));
Assert.False(reader.Read());
}
}
......@@ -789,7 +823,7 @@ public async Task Issue563_QueryAsyncShouldThrowException()
try
{
var data = (await connection.QueryAsync<int>("select 1 union all select 2; RAISERROR('after select', 16, 1);").ConfigureAwait(false)).ToList();
Assert.Fail();
Assert.True(false, "Expected Exception");
}
catch (SqlException ex) when (ex.Message == "after select") { /* swallow only this */ }
}
......
......@@ -12,26 +12,26 @@ public void TestAbstractInheritance()
{
var order = connection.Query<AbstractInheritance.ConcreteOrder>("select 1 Internal,2 Protected,3 [Public],4 Concrete").First();
order.Internal.IsEqualTo(1);
order.ProtectedVal.IsEqualTo(2);
order.Public.IsEqualTo(3);
order.Concrete.IsEqualTo(4);
Assert.Equal(1, order.Internal);
Assert.Equal(2, order.ProtectedVal);
Assert.Equal(3, order.Public);
Assert.Equal(4, order.Concrete);
}
[Fact]
public void TestMultipleConstructors()
{
MultipleConstructors mult = connection.Query<MultipleConstructors>("select 0 A, 'Dapper' b").First();
mult.A.IsEqualTo(0);
mult.B.IsEqualTo("Dapper");
Assert.Equal(0, mult.A);
Assert.Equal("Dapper", mult.B);
}
[Fact]
public void TestConstructorsWithAccessModifiers()
{
ConstructorsWithAccessModifiers value = connection.Query<ConstructorsWithAccessModifiers>("select 0 A, 'Dapper' b").First();
value.A.IsEqualTo(1);
value.B.IsEqualTo("Dapper!");
Assert.Equal(1, value.A);
Assert.Equal("Dapper!", value.B);
}
[Fact]
......@@ -39,11 +39,11 @@ public void TestNoDefaultConstructor()
{
var guid = Guid.NewGuid();
NoDefaultConstructor nodef = connection.Query<NoDefaultConstructor>("select CAST(NULL AS integer) A1, CAST(NULL AS integer) b1, CAST(NULL AS real) f1, 'Dapper' s1, G1 = @id", new { id = guid }).First();
nodef.A.IsEqualTo(0);
nodef.B.IsEqualTo(null);
nodef.F.IsEqualTo(0);
nodef.S.IsEqualTo("Dapper");
nodef.G.IsEqualTo(guid);
Assert.Equal(0, nodef.A);
Assert.Null(nodef.B);
Assert.Equal(0, nodef.F);
Assert.Equal("Dapper", nodef.S);
Assert.Equal(nodef.G, guid);
}
[Fact]
......@@ -52,18 +52,18 @@ public void TestNoDefaultConstructorWithChar()
const char c1 = 'ą';
const char c3 = 'ó';
NoDefaultConstructorWithChar nodef = connection.Query<NoDefaultConstructorWithChar>("select @c1 c1, @c2 c2, @c3 c3", new { c1 = c1, c2 = (char?)null, c3 = c3 }).First();
nodef.Char1.IsEqualTo(c1);
nodef.Char2.IsEqualTo(null);
nodef.Char3.IsEqualTo(c3);
Assert.Equal(nodef.Char1, c1);
Assert.Null(nodef.Char2);
Assert.Equal(nodef.Char3, c3);
}
[Fact]
public void TestNoDefaultConstructorWithEnum()
{
NoDefaultConstructorWithEnum nodef = connection.Query<NoDefaultConstructorWithEnum>("select cast(2 as smallint) E1, cast(5 as smallint) n1, cast(null as smallint) n2").First();
nodef.E.IsEqualTo(ShortEnum.Two);
nodef.NE1.IsEqualTo(ShortEnum.Five);
nodef.NE2.IsEqualTo(null);
Assert.Equal(ShortEnum.Two, nodef.E);
Assert.Equal(ShortEnum.Five, nodef.NE1);
Assert.Null(nodef.NE2);
}
[Fact]
......@@ -77,10 +77,10 @@ public void ExplicitConstructors()
SELECT * FROM @ExplicitConstructors"
).ToList();
rows.Count.IsEqualTo(1);
rows[0].Field.IsEqualTo(1);
rows[0].Field_1.IsEqualTo(1);
rows[0].GetWentThroughProperConstructor().IsTrue();
Assert.Single(rows);
Assert.Equal(1, rows[0].Field);
Assert.Equal(1, rows[0].Field_1);
Assert.True(rows[0].GetWentThroughProperConstructor());
}
private class _ExplicitConstructors
......@@ -104,107 +104,6 @@ public bool GetWentThroughProperConstructor()
}
}
#if LINQ2SQL
private class NoDefaultConstructorWithBinary
{
public System.Data.Linq.Binary Value { get; set; }
public int Ynt { get; set; }
public NoDefaultConstructorWithBinary(System.Data.Linq.Binary val)
{
Value = val;
}
}
[Fact]
public void TestNoDefaultConstructorBinary()
{
byte[] orig = new byte[20];
new Random(123456).NextBytes(orig);
var input = new System.Data.Linq.Binary(orig);
var output = connection.Query<NoDefaultConstructorWithBinary>("select @input as val", new { input }).First().Value;
output.ToArray().IsSequenceEqualTo(orig);
}
#endif
[Fact]
public void Issue461_TypeHandlerWorksInConstructor()
{
SqlMapper.AddTypeHandler(new Issue461_BlargHandler());
connection.Execute(@"CREATE TABLE #Issue461 (
Id int not null IDENTITY(1,1),
SomeValue nvarchar(50),
SomeBlargValue nvarchar(200),
)");
const string Expected = "abc123def";
var blarg = new Blarg(Expected);
connection.Execute(
"INSERT INTO #Issue461 (SomeValue, SomeBlargValue) VALUES (@value, @blarg)",
new { value = "what up?", blarg });
// test: without constructor
var parameterlessWorks = connection.QuerySingle<Issue461_ParameterlessTypeConstructor>("SELECT * FROM #Issue461");
parameterlessWorks.Id.IsEqualTo(1);
parameterlessWorks.SomeValue.IsEqualTo("what up?");
parameterlessWorks.SomeBlargValue.Value.IsEqualTo(Expected);
// test: via constructor
var parameterDoesNot = connection.QuerySingle<Issue461_ParameterisedTypeConstructor>("SELECT * FROM #Issue461");
parameterDoesNot.Id.IsEqualTo(1);
parameterDoesNot.SomeValue.IsEqualTo("what up?");
parameterDoesNot.SomeBlargValue.Value.IsEqualTo(Expected);
}
// I would usually expect this to be a struct; using a class
// so that we can't pass unexpectedly due to forcing an unsafe cast - want
// to see an InvalidCastException if it is wrong
private class Blarg
{
public Blarg(string value) { Value = value; }
public string Value { get; }
public override string ToString()
{
return Value;
}
}
private class Issue461_BlargHandler : SqlMapper.TypeHandler<Blarg>
{
public override void SetValue(IDbDataParameter parameter, Blarg value)
{
parameter.Value = ((object)value.Value) ?? DBNull.Value;
}
public override Blarg Parse(object value)
{
string s = (value == null || value is DBNull) ? null : Convert.ToString(value);
return new Blarg(s);
}
}
private class Issue461_ParameterlessTypeConstructor
{
public int Id { get; set; }
public string SomeValue { get; set; }
public Blarg SomeBlargValue { get; set; }
}
private class Issue461_ParameterisedTypeConstructor
{
public Issue461_ParameterisedTypeConstructor(int id, string someValue, Blarg someBlargValue)
{
Id = id;
SomeValue = someValue;
SomeBlargValue = someBlargValue;
}
public int Id { get; }
public string SomeValue { get; }
public Blarg SomeBlargValue { get; }
}
public static class AbstractInheritance
{
public abstract class Order
......@@ -312,7 +211,7 @@ private WithPrivateConstructor()
public void TestWithNonPublicConstructor()
{
var output = connection.Query<WithPrivateConstructor>("select 1 as Foo").First();
output.Foo.IsEqualTo(1);
Assert.Equal(1, output.Foo);
}
}
}
......@@ -6,14 +6,12 @@
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<TargetFrameworks>net452;netcoreapp1.0</TargetFrameworks>
<TargetFrameworks>net452;netcoreapp1.0;netcoreapp2.0</TargetFrameworks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net452' ">
<DefineConstants>$(DefineConstants);NET45;MYSQL;ENTITY_FRAMEWORK;LINQ2SQL;FIREBIRD;SQL_CE;POSTGRESQL;OLEDB;SQLITE</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<DefineConstants>$(DefineConstants);COREFX</DefineConstants>
<DefineConstants>$(DefineConstants);ENTITY_FRAMEWORK;LINQ2SQL;SQL_CE;OLEDB</DefineConstants>
</PropertyGroup>
<ItemGroup>
<None Remove="Test.DB.sdf" />
......@@ -21,23 +19,22 @@
<ItemGroup>
<ProjectReference Include="..\Dapper\Dapper.csproj" />
<ProjectReference Include="..\Dapper.Contrib\Dapper.Contrib.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.3.0-beta1-build3642" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.0-beta1-build1309" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.0-beta1-build3642" />
<PackageReference Include="FirebirdSql.Data.FirebirdClient" Version="5.9.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
<PackageReference Include="MySql.Data" Version="8.0.8-dmr" />
<PackageReference Include="Npgsql" Version="3.2.5" />
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
<PackageReference Include="xunit" Version="$(xUnitVersion)" />
<PackageReference Include="xunit.runner.visualstudio" Version="$(xUnitVersion)" />
<DotNetCliToolReference Include="dotnet-xunit" Version="$(xUnitVersion)" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
<ProjectReference Include="..\Dapper.EntityFramework\Dapper.EntityFramework.csproj" />
<PackageReference Include="EntityFramework" Version="6.1.3" />
<PackageReference Include="FirebirdSql.Data.FirebirdClient" Version="5.8.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="1.1.1" />
<PackageReference Include="Microsoft.SqlServer.Compact" Version="4.0.8876.1" />
<PackageReference Include="Microsoft.SqlServer.Types" Version="14.0.314.76" />
<PackageReference Include="MySql.Data" Version="7.0.7-m61" />
<PackageReference Include="Npgsql" Version="3.2.2" />
<PackageReference Include="System.Data.SQLite" Version="1.0.104" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Data.Linq" />
......@@ -47,9 +44,12 @@
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
<PackageReference Include="System.Ben" Version="1.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="1.1.0" />
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp1.0'">
<PackageReference Include="Microsoft.Data.Sqlite" Version="1.1.1" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp2.0'">
<PackageReference Include="Microsoft.Data.Sqlite" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
......
......@@ -4,7 +4,7 @@
namespace Dapper.Tests
{
public partial class DataReaderTests : TestBase
public class DataReaderTests : TestBase
{
[Fact]
public void GetSameReaderForSameShape()
......@@ -14,12 +14,12 @@ public void GetSameReaderForSameShape()
var typedParser = origReader.GetRowParser<HazNameId>();
ReferenceEquals(origParser, typedParser).IsEqualTo(true);
Assert.True(ReferenceEquals(origParser, typedParser));
var list = origReader.Parse<HazNameId>().ToList();
list.Count.IsEqualTo(1);
list[0].Name.IsEqualTo("abc");
list[0].Id.IsEqualTo(123);
Assert.Single(list);
Assert.Equal("abc", list[0].Name);
Assert.Equal(123, list[0].Id);
origReader.Dispose();
var secondReader = connection.ExecuteReader("select 'abc' as Name, 123 as Id");
......@@ -27,15 +27,15 @@ public void GetSameReaderForSameShape()
var thirdParser = secondReader.GetRowParser(typeof(HazNameId), 1);
list = secondReader.Parse<HazNameId>().ToList();
list.Count.IsEqualTo(1);
list[0].Name.IsEqualTo("abc");
list[0].Id.IsEqualTo(123);
Assert.Single(list);
Assert.Equal("abc", list[0].Name);
Assert.Equal(123, list[0].Id);
secondReader.Dispose();
// now: should be different readers, but same parser
ReferenceEquals(origReader, secondReader).IsEqualTo(false);
ReferenceEquals(origParser, secondParser).IsEqualTo(true);
ReferenceEquals(secondParser, thirdParser).IsEqualTo(false);
Assert.False(ReferenceEquals(origReader, secondReader));
Assert.True(ReferenceEquals(origParser, secondParser));
Assert.False(ReferenceEquals(secondParser, thirdParser));
}
[Fact]
......@@ -68,13 +68,13 @@ union all
}
}
result.Count.IsEqualTo(2);
result[0].Type.IsEqualTo(1);
result[1].Type.IsEqualTo(2);
Assert.Equal(2, result.Count);
Assert.Equal(1, result[0].Type);
Assert.Equal(2, result[1].Type);
var foo = (Discriminated_Foo)result[0];
foo.Name.IsEqualTo("abc");
Assert.Equal("abc", foo.Name);
var bar = (Discriminated_Bar)result[1];
bar.Value.IsEqualTo((float)4.0);
Assert.Equal(bar.Value, (float)4.0);
}
[Fact]
......@@ -108,7 +108,7 @@ union all
break;
}
obj.IsNotNull();
Assert.NotNull(obj);
obj.HazNameIdObject = toHaz(reader);
result.Add(obj);
......@@ -116,17 +116,17 @@ union all
}
}
result.Count.IsEqualTo(2);
result[0].Type.IsEqualTo(1);
result[1].Type.IsEqualTo(2);
Assert.Equal(2, result.Count);
Assert.Equal(1, result[0].Type);
Assert.Equal(2, result[1].Type);
var foo = (DiscriminatedWithMultiMapping_Foo)result[0];
foo.Name.IsEqualTo("abc");
foo.HazNameIdObject.Id.IsEqualTo(1);
foo.HazNameIdObject.Name.IsEqualTo("zxc");
Assert.Equal("abc", foo.Name);
Assert.Equal(1, foo.HazNameIdObject.Id);
Assert.Equal("zxc", foo.HazNameIdObject.Name);
var bar = (DiscriminatedWithMultiMapping_Bar)result[1];
bar.Value.IsEqualTo((float)4.0);
bar.HazNameIdObject.Id.IsEqualTo(2);
bar.HazNameIdObject.Name.IsEqualTo("qwe");
Assert.Equal(bar.Value, (float)4.0);
Assert.Equal(2, bar.HazNameIdObject.Id);
Assert.Equal("qwe", bar.HazNameIdObject.Name);
}
private abstract class Discriminated_BaseType
......@@ -137,18 +137,13 @@ private abstract class Discriminated_BaseType
private class Discriminated_Foo : Discriminated_BaseType
{
public string Name { get; set; }
public override int Type {
get { return 1; }
}
public override int Type => 1;
}
private class Discriminated_Bar : Discriminated_BaseType
{
public float Value { get; set; }
public override int Type
{
get { return 2; }
}
public override int Type => 2;
}
private abstract class DiscriminatedWithMultiMapping_BaseType : Discriminated_BaseType
......@@ -160,20 +155,14 @@ private class DiscriminatedWithMultiMapping_Foo : DiscriminatedWithMultiMapping_
{
public override HazNameId HazNameIdObject { get; set; }
public string Name { get; set; }
public override int Type
{
get { return 1; }
}
public override int Type => 1;
}
private class DiscriminatedWithMultiMapping_Bar : DiscriminatedWithMultiMapping_BaseType
{
public override HazNameId HazNameIdObject { get; set; }
public float Value { get; set; }
public override int Type
{
get { return 2; }
}
public override int Type => 2;
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Dapper.Tests
......@@ -18,7 +15,7 @@ public void Issue261_Decimals()
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);
Assert.Equal(11.884M, c);
}
[Fact]
......@@ -64,7 +61,7 @@ private void Issue261_Decimals_ADONET(bool setPrecisionScaleViaAbstractApi)
cmd.Parameters.Add(c);
cmd.ExecuteNonQuery();
decimal value = (decimal)c.Value;
value.IsEqualTo(11.884M);
Assert.Equal(11.884M, value);
}
}
......@@ -72,7 +69,7 @@ private void Issue261_Decimals_ADONET(bool setPrecisionScaleViaAbstractApi)
public void BasicDecimals()
{
var c = connection.Query<decimal>("select @c", new { c = 11.884M }).Single();
c.IsEqualTo(11.884M);
Assert.Equal(11.884M, c);
}
[Fact]
......@@ -103,9 +100,9 @@ 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();
Assert.Null(row.B);
row.C.Equals(0.0M);
row.D.IsNull();
Assert.Null(row.D);
}
private class HasDoubleDecimal
......
......@@ -9,42 +9,42 @@ public class EnumTests : TestBase
[Fact]
public void TestEnumWeirdness()
{
connection.Query<TestEnumClass>("select null as [EnumEnum]").First().EnumEnum.IsEqualTo(null);
connection.Query<TestEnumClass>("select cast(1 as tinyint) as [EnumEnum]").First().EnumEnum.IsEqualTo(TestEnum.Bla);
Assert.Null(connection.Query<TestEnumClass>("select null as [EnumEnum]").First().EnumEnum);
Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClass>("select cast(1 as tinyint) as [EnumEnum]").First().EnumEnum);
}
[Fact]
public void TestEnumStrings()
{
connection.Query<TestEnumClassNoNull>("select 'BLA' as [EnumEnum]").First().EnumEnum.IsEqualTo(TestEnum.Bla);
connection.Query<TestEnumClassNoNull>("select 'bla' as [EnumEnum]").First().EnumEnum.IsEqualTo(TestEnum.Bla);
Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClassNoNull>("select 'BLA' as [EnumEnum]").First().EnumEnum);
Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClassNoNull>("select 'bla' as [EnumEnum]").First().EnumEnum);
connection.Query<TestEnumClass>("select 'BLA' as [EnumEnum]").First().EnumEnum.IsEqualTo(TestEnum.Bla);
connection.Query<TestEnumClass>("select 'bla' as [EnumEnum]").First().EnumEnum.IsEqualTo(TestEnum.Bla);
Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClass>("select 'BLA' as [EnumEnum]").First().EnumEnum);
Assert.Equal(TestEnum.Bla, connection.Query<TestEnumClass>("select 'bla' as [EnumEnum]").First().EnumEnum);
}
[Fact]
public void TestEnumParamsWithNullable()
{
EnumParam a = EnumParam.A;
const EnumParam a = EnumParam.A;
EnumParam? b = EnumParam.B, c = null;
var obj = connection.Query<EnumParamObject>("select @a as A, @b as B, @c as C",
new { a, b, c }).Single();
obj.A.IsEqualTo(EnumParam.A);
obj.B.IsEqualTo(EnumParam.B);
obj.C.IsEqualTo(null);
Assert.Equal(EnumParam.A, obj.A);
Assert.Equal(EnumParam.B, obj.B);
Assert.Null(obj.C);
}
[Fact]
public void TestEnumParamsWithoutNullable()
{
EnumParam a = EnumParam.A;
EnumParam b = EnumParam.B, c = 0;
const EnumParam a = EnumParam.A;
const EnumParam b = EnumParam.B, c = 0;
var obj = connection.Query<EnumParamObjectNonNullable>("select @a as A, @b as B, @c as C",
new { a, b, c }).Single();
obj.A.IsEqualTo(EnumParam.A);
obj.B.IsEqualTo(EnumParam.B);
obj.C.IsEqualTo((EnumParam)0);
Assert.Equal(EnumParam.A, obj.A);
Assert.Equal(EnumParam.B, obj.B);
Assert.Equal(obj.C, (EnumParam)0);
}
private enum EnumParam : short
......@@ -96,7 +96,7 @@ public void AdoNetEnumValue()
cmd.Parameters.Add(p);
object value = cmd.ExecuteScalar();
AnEnum val = (AnEnum)value;
val.IsEqualTo(AnEnum.B);
Assert.Equal(AnEnum.B, val);
}
}
......@@ -123,7 +123,7 @@ public SO27024806Class(SO27024806Enum myField)
public void SO27024806_TestVarcharEnumMemberWithExplicitConstructor()
{
var foo = connection.Query<SO27024806Class>("SELECT 'Foo' AS myField").Single();
foo.MyField.IsEqualTo(SO27024806Enum.Foo);
Assert.Equal(SO27024806Enum.Foo, foo.MyField);
}
}
}
using System.Collections.Generic;
namespace Dapper.Tests
{
public static class Assert
{
public static void IsEqualTo<T>(this T actual, T expected)
{
Xunit.Assert.Equal(expected, actual);
}
public static void IsSequenceEqualTo<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
Xunit.Assert.Equal(expected, actual ?? new T[0]);
}
public static void IsMoreThan(this int a, int b)
{
Xunit.Assert.True(a > b, $"{a} should be larger than {b}");
}
public static void IsMoreThan(this long a, int b)
{
Xunit.Assert.True(a > b, $"{a} should be larger than {b}");
}
public static void Fail(string message = null)
{
Xunit.Assert.True(false, message ?? "Expectation failed");
}
public static void IsFalse(this bool b)
{
Xunit.Assert.False(b);
}
public static void IsTrue(this bool b)
{
Xunit.Assert.True(b);
}
public static void IsNull(this object obj)
{
Xunit.Assert.Null(obj);
}
public static void IsNotNull(this object obj)
{
Xunit.Assert.NotNull(obj);
}
}
}
......@@ -4,20 +4,6 @@
namespace Dapper.Tests
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class FactUnlessCoreCLRAttribute : FactAttribute
{
public FactUnlessCoreCLRAttribute(string url)
{
#if COREFX
Skip = $"CoreFX: {url}";
#endif
this.Url = url;
}
public string Url { get; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class FactLongRunningAttribute : FactAttribute
{
......@@ -31,6 +17,7 @@ public FactLongRunningAttribute()
public string Url { get; private set; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class FactRequiredCompatibilityLevelAttribute : FactAttribute
{
public FactRequiredCompatibilityLevelAttribute(int level) : base()
......@@ -56,6 +43,7 @@ static FactRequiredCompatibilityLevelAttribute()
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class FactUnlessCaseSensitiveDatabaseAttribute : FactAttribute
{
public FactUnlessCaseSensitiveDatabaseAttribute() : base()
......
using System;
using System.Data;
using System.Data.Common;
using Xunit;
namespace Dapper.Tests
{
......@@ -12,48 +13,48 @@ public static void DapperEnumValue(IDbConnection connection)
{
// test passing as AsEnum, reading as int
var v = (AnEnum)connection.QuerySingle<int>("select @v, @y, @z", new { v = AnEnum.B, y = (AnEnum?)AnEnum.B, z = (AnEnum?)null });
v.IsEqualTo(AnEnum.B);
Assert.Equal(AnEnum.B, v);
var args = new DynamicParameters();
args.Add("v", AnEnum.B);
args.Add("y", AnEnum.B);
args.Add("z", null);
v = (AnEnum)connection.QuerySingle<int>("select @v, @y, @z", args);
v.IsEqualTo(AnEnum.B);
Assert.Equal(AnEnum.B, v);
// test passing as int, reading as AnEnum
var k = (int)connection.QuerySingle<AnEnum>("select @v, @y, @z", new { v = (int)AnEnum.B, y = (int?)(int)AnEnum.B, z = (int?)null });
k.IsEqualTo((int)AnEnum.B);
Assert.Equal(k, (int)AnEnum.B);
args = new DynamicParameters();
args.Add("v", (int)AnEnum.B);
args.Add("y", (int)AnEnum.B);
args.Add("z", null);
k = (int)connection.QuerySingle<AnEnum>("select @v, @y, @z", args);
k.IsEqualTo((int)AnEnum.B);
Assert.Equal(k, (int)AnEnum.B);
}
public static void TestDateTime(DbConnection connection)
{
DateTime? now = DateTime.UtcNow;
try { connection.Execute("DROP TABLE Persons"); } catch { /* don't care */ }
connection.Execute(@"CREATE TABLE Persons (id int not null, dob datetime null)");
connection.Execute(@"INSERT Persons (id, dob) values (@id, @dob)",
connection.Execute("CREATE TABLE Persons (id int not null, dob datetime null)");
connection.Execute("INSERT Persons (id, dob) values (@id, @dob)",
new { id = 7, dob = (DateTime?)null });
connection.Execute(@"INSERT Persons (id, dob) values (@id, @dob)",
connection.Execute("INSERT Persons (id, dob) values (@id, @dob)",
new { id = 42, dob = now });
var row = connection.QueryFirstOrDefault<NullableDatePerson>(
"SELECT id, dob, dob as dob2 FROM Persons WHERE id=@id", new { id = 7 });
row.IsNotNull();
row.Id.IsEqualTo(7);
row.DoB.IsNull();
row.DoB2.IsNull();
Assert.NotNull(row);
Assert.Equal(7, row.Id);
Assert.Null(row.DoB);
Assert.Null(row.DoB2);
row = connection.QueryFirstOrDefault<NullableDatePerson>(
"SELECT id, dob FROM Persons WHERE id=@id", new { id = 42 });
row.IsNotNull();
row.Id.IsEqualTo(42);
Assert.NotNull(row);
Assert.Equal(42, row.Id);
row.DoB.Equals(now);
row.DoB2.Equals(now);
}
......
......@@ -38,10 +38,10 @@ public void LiteralReplacementDynamicEnumAndString()
public void LiteralReplacementBoolean()
{
var row = connection.Query<int?>("select 42 where 1 = {=val}", new { val = true }).SingleOrDefault();
row.IsNotNull();
row.IsEqualTo(42);
Assert.NotNull(row);
Assert.Equal(42, row);
row = connection.Query<int?>("select 42 where 1 = {=val}", new { val = false }).SingleOrDefault();
row.IsNull();
Assert.Null(row);
}
[Fact]
......@@ -67,7 +67,7 @@ public void LiteralIn()
});
var count = connection.Query<int>("select count(1) from #literalin where id in {=ids}",
new { ids = new[] { 1, 3, 4 } }).Single();
count.IsEqualTo(2);
Assert.Equal(2, count);
}
[Fact]
......@@ -78,9 +78,9 @@ public void LiteralReplacement()
var rows = new[] { new { id = 1, foo = 2 }, new { id = 3, foo = 4 } };
connection.Execute("insert #literal1 (id,foo) values ({=id}, @foo)", rows);
var count = connection.Query<int>("select count(1) from #literal1 where id={=foo}", new { foo = 123 }).Single();
count.IsEqualTo(1);
Assert.Equal(1, count);
int sum = connection.Query<int>("select sum(id) + sum(foo) from #literal1").Single();
sum.IsEqualTo(123 + 456 + 1 + 2 + 3 + 4);
Assert.Equal(sum, 123 + 456 + 1 + 2 + 3 + 4);
}
[Fact]
......@@ -94,7 +94,7 @@ public void LiteralReplacementDynamic()
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);
Assert.Equal(1, count);
}
}
}
......@@ -8,7 +8,7 @@
using System.Linq;
using Xunit;
#if COREFX
#if NETCOREAPP1_0
using System.Collections;
using System.Dynamic;
using System.Data.SqlTypes;
......@@ -18,7 +18,7 @@
using System.Threading.Tasks;
#endif
#if COREFX
#if NETCOREAPP1_0
namespace System
{
public enum GenericUriParserOptions
......@@ -46,11 +46,11 @@ public class MiscTests : TestBase
public void TestNullableGuidSupport()
{
var guid = connection.Query<Guid?>("select null").First();
guid.IsNull();
Assert.Null(guid);
guid = Guid.NewGuid();
var guid2 = connection.Query<Guid?>("select @guid", new { guid }).First();
guid.IsEqualTo(guid2);
Assert.Equal(guid, guid2);
}
[Fact]
......@@ -58,7 +58,7 @@ public void TestNonNullableGuidSupport()
{
var guid = Guid.NewGuid();
var guid2 = connection.Query<Guid?>("select @guid", new { guid }).First();
Assert.IsTrue(guid == guid2);
Assert.True(guid == guid2);
}
private struct Car
......@@ -88,9 +88,9 @@ 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);
Assert.Equal(21, car.Age);
Assert.Equal("Ford", car.Name);
Assert.Equal(2, (int)car.Trap);
}
[Fact]
......@@ -100,16 +100,15 @@ public void TestStructAsParam()
// 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);
Assert.Equal(car2.Name, car1.Name);
Assert.Equal(car2.Age, car1.Age);
Assert.Equal(car2.Trap, car1.Trap);
}
[Fact]
public void SelectListInt()
{
connection.Query<int>("select 1 union all select 2 union all select 3")
.IsSequenceEqualTo(new[] { 1, 2, 3 });
Assert.Equal(new[] { 1, 2, 3 }, connection.Query<int>("select 1 union all select 2 union all select 3"));
}
[Fact]
......@@ -125,12 +124,12 @@ public void TestSchemaChanged()
try
{
var d = connection.Query<Dog>("select * from #dog").Single();
d.Name.IsEqualTo("Alf");
d.Age.IsEqualTo(1);
Assert.Equal("Alf", d.Name);
Assert.Equal(1, d.Age);
connection.Execute("alter table #dog drop column Name");
d = connection.Query<Dog>("select * from #dog").Single();
d.Name.IsNull();
d.Age.IsEqualTo(1);
Assert.Null(d.Name);
Assert.Equal(1, d.Age);
}
finally
{
......@@ -145,12 +144,12 @@ public void TestSchemaChangedViaFirstOrDefault()
try
{
var d = connection.QueryFirstOrDefault<Dog>("select * from #dog");
d.Name.IsEqualTo("Alf");
d.Age.IsEqualTo(1);
Assert.Equal("Alf", d.Name);
Assert.Equal(1, d.Age);
connection.Execute("alter table #dog drop column Name");
d = connection.QueryFirstOrDefault<Dog>("select * from #dog");
d.Name.IsNull();
d.Age.IsEqualTo(1);
Assert.Null(d.Name);
Assert.Equal(1, d.Age);
}
finally
{
......@@ -162,29 +161,38 @@ public void TestSchemaChangedViaFirstOrDefault()
public void Test_Single_First_Default()
{
var sql = "select 0 where 1 = 0;"; // no rows
try { connection.QueryFirst<int>(sql); Assert.Fail("QueryFirst, 0"); } catch (InvalidOperationException ex) { ex.Message.IsEqualTo("Sequence contains no elements"); }
try { connection.QuerySingle<int>(sql); Assert.Fail("QuerySingle, 0"); } catch (InvalidOperationException ex) { ex.Message.IsEqualTo("Sequence contains no elements"); }
connection.QueryFirstOrDefault<int>(sql).IsEqualTo(0);
connection.QuerySingleOrDefault<int>(sql).IsEqualTo(0);
var ex = Assert.Throws<InvalidOperationException>(() => connection.QueryFirst<int>(sql));
Assert.Equal("Sequence contains no elements", ex.Message);
ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingle<int>(sql));
Assert.Equal("Sequence contains no elements", ex.Message);
Assert.Equal(0, connection.QueryFirstOrDefault<int>(sql));
Assert.Equal(0, connection.QuerySingleOrDefault<int>(sql));
sql = "select 1;"; // one row
connection.QueryFirst<int>(sql).IsEqualTo(1);
connection.QuerySingle<int>(sql).IsEqualTo(1);
connection.QueryFirstOrDefault<int>(sql).IsEqualTo(1);
connection.QuerySingleOrDefault<int>(sql).IsEqualTo(1);
Assert.Equal(1, connection.QueryFirst<int>(sql));
Assert.Equal(1, connection.QuerySingle<int>(sql));
Assert.Equal(1, connection.QueryFirstOrDefault<int>(sql));
Assert.Equal(1, connection.QuerySingleOrDefault<int>(sql));
sql = "select 2 union select 3 order by 1;"; // two rows
connection.QueryFirst<int>(sql).IsEqualTo(2);
try { connection.QuerySingle<int>(sql); Assert.Fail("QuerySingle, 2"); } catch (InvalidOperationException ex) { ex.Message.IsEqualTo("Sequence contains more than one element"); }
connection.QueryFirstOrDefault<int>(sql).IsEqualTo(2);
try { connection.QuerySingleOrDefault<int>(sql); Assert.Fail("QuerySingleOrDefault, 2"); } catch (InvalidOperationException ex) { ex.Message.IsEqualTo("Sequence contains more than one element"); }
Assert.Equal(2, connection.QueryFirst<int>(sql));
ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingle<int>(sql));
Assert.Equal("Sequence contains more than one element", ex.Message);
Assert.Equal(2, connection.QueryFirstOrDefault<int>(sql));
ex = Assert.Throws<InvalidOperationException>(() => connection.QuerySingleOrDefault<int>(sql));
Assert.Equal("Sequence contains more than one element", ex.Message);
}
[Fact]
public void TestStrings()
{
connection.Query<string>(@"select 'a' a union select 'b'")
.IsSequenceEqualTo(new[] { "a", "b" });
Assert.Equal(new[] { "a", "b" }, connection.Query<string>("select 'a' a union select 'b'"));
}
// see https://stackoverflow.com/questions/16726709/string-format-with-sql-wildcard-causing-dapper-query-to-break
......@@ -203,8 +211,8 @@ public void CheckComplexConcat()
SELECT * FROM #users16726709
WHERE (first_name LIKE {0} OR last_name LIKE {0});";
const string use_end_only = @"CONCAT(@search_term, '%')";
const string use_both = @"CONCAT('%', @search_term, '%')";
const string use_end_only = "CONCAT(@search_term, '%')";
const string use_both = "CONCAT('%', @search_term, '%')";
// if true, slower query due to not being able to use indices, but will allow searching inside strings
const bool allow_start_wildcards = false;
......@@ -216,9 +224,9 @@ public void CheckComplexConcat()
insert #users16726709 values ('Fred','Bloggs') insert #users16726709 values ('Tony','Farcus') insert #users16726709 values ('Albert','TenoF')");
// 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);
Assert.Equal(2, connection.Query(end_wildcard, new { search_term = term }).Count());
Assert.Equal(3, connection.Query(both_wildcards, new { search_term = term }).Count());
Assert.Equal(2, connection.Query(query, new { search_term = term }).Count());
}
[Fact]
......@@ -227,9 +235,9 @@ public void TestExtraFields()
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select '' as Extra, 1 as Age, 0.1 as Name1 , Id = @id", new { id = guid });
dog.Count().IsEqualTo(1);
dog.First().Age.IsEqualTo(1);
dog.First().Id.IsEqualTo(guid);
Assert.Single(dog);
Assert.Equal(1, dog.First().Age);
Assert.Equal(dog.First().Id, guid);
}
[Fact]
......@@ -238,15 +246,15 @@ public void TestStrongType()
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
dog.Count().IsEqualTo(1);
dog.First().Age.IsNull();
dog.First().Id.IsEqualTo(guid);
Assert.Single(dog);
Assert.Null(dog.First().Age);
Assert.Equal(dog.First().Id, guid);
}
[Fact]
public void TestSimpleNull()
{
connection.Query<DateTime?>("select null").First().IsNull();
Assert.Null(connection.Query<DateTime?>("select null").First());
}
[Fact]
......@@ -254,33 +262,36 @@ public void TestExpando()
{
var rows = connection.Query("select 1 A, 2 B union all select 3, 4").ToList();
((int)rows[0].A).IsEqualTo(1);
((int)rows[0].B).IsEqualTo(2);
((int)rows[1].A).IsEqualTo(3);
((int)rows[1].B).IsEqualTo(4);
Assert.Equal(1, (int)rows[0].A);
Assert.Equal(2, (int)rows[0].B);
Assert.Equal(3, (int)rows[1].A);
Assert.Equal(4, (int)rows[1].B);
}
[Fact]
public void TestStringList()
{
Assert.Equal(
new[] { "a", "b", "c" },
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" });
);
Assert.Equal(
new string[0],
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]);
);
}
[Fact]
public void TestExecuteCommand()
{
connection.Execute(@"
Assert.Equal(2, connection.Execute(@"
set nocount on
create table #t(i int)
set nocount off
insert #t
select @a a union all select @b
set nocount on
drop table #t", new { a = 1, b = 2 }).IsEqualTo(2);
drop table #t", new { a = 1, b = 2 }));
}
[Fact]
......@@ -289,10 +300,10 @@ public void TestExecuteMultipleCommand()
connection.Execute("create table #t(i int)");
try
{
int tally = connection.Execute(@"insert #t (i) values(@a)", new[] { new { a = 1 }, new { a = 2 }, new { a = 3 }, new { a = 4 } });
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);
Assert.Equal(4, tally);
Assert.Equal(10, sum);
}
finally
{
......@@ -312,14 +323,14 @@ public void TestExecuteMultipleCommandStrongType()
connection.Execute("create table #t(Name nvarchar(max), Age int)");
try
{
int tally = connection.Execute(@"insert #t (Name,Age) values(@Name, @Age)", new List<Student>
int tally = connection.Execute("insert #t (Name,Age) values(@Name, @Age)", new List<Student>
{
new Student{Age = 1, Name = "sam"},
new Student{Age = 2, Name = "bob"}
});
int sum = connection.Query<int>("select sum(Age) from #t").First();
tally.IsEqualTo(2);
sum.IsEqualTo(3);
Assert.Equal(2, tally);
Assert.Equal(3, sum);
}
finally
{
......@@ -331,10 +342,10 @@ public void TestExecuteMultipleCommandStrongType()
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 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);
Assert.Equal(4, tally);
Assert.Equal(10, sum);
}
private class TestObj
......@@ -357,21 +368,21 @@ private int Priv
[Fact]
public void TestSetInternal()
{
connection.Query<TestObj>("select 10 as [Internal]").First()._internal.IsEqualTo(10);
Assert.Equal(10, connection.Query<TestObj>("select 10 as [Internal]").First()._internal);
}
[Fact]
public void TestSetPrivate()
{
connection.Query<TestObj>("select 10 as [Priv]").First()._priv.IsEqualTo(10);
Assert.Equal(10, connection.Query<TestObj>("select 10 as [Priv]").First()._priv);
}
[Fact]
public void TestExpandWithNullableFields()
{
var row = connection.Query("select null A, 2 B").Single();
((int?)row.A).IsNull();
((int?)row.B).IsEqualTo(2);
Assert.Null((int?)row.A);
Assert.Equal(2, (int?)row.B);
}
[Fact]
......@@ -398,7 +409,7 @@ public void TestEnumeration()
// should not exception, since enumerated
en = connection.Query<int>("select 1 as one", buffered: false);
gotException.IsTrue();
Assert.True(gotException);
}
[Fact]
......@@ -425,7 +436,7 @@ public void TestEnumerationDynamic()
// should not exception, since enumertated
en = connection.Query("select 1 as one", buffered: false);
gotException.IsTrue();
Assert.True(gotException);
}
[Fact]
......@@ -433,7 +444,7 @@ public void TestNakedBigInt()
{
const long foo = 12345;
var result = connection.Query<long>("select @foo", new { foo }).Single();
foo.IsEqualTo(result);
Assert.Equal(foo, result);
}
[Fact]
......@@ -444,7 +455,7 @@ public void TestBigIntMember()
declare @bar table(Value bigint)
insert @bar values (@foo)
select * from @bar", new { foo }).Single();
result.Value.IsEqualTo(foo);
Assert.Equal(result.Value, foo);
}
private class WithBigInt
......@@ -456,12 +467,12 @@ private class WithBigInt
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);
"select a=1,b=2,c=3,d=4,f='5'").Single();
Assert.Equal(1, data.a);
Assert.Equal(2, data.GetB());
Assert.Equal(3, data.c);
Assert.Equal(4, data.GetD());
Assert.Equal(5, data.e);
}
private class TestFieldCaseAndPrivatesEntity
......@@ -501,24 +512,24 @@ 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");
Assert.Equal("One", list.First().Derived1);
Assert.Equal("Two", list.First().Derived2);
Assert.Equal("Three", list.First().Base1);
Assert.Equal("Four", list.First().Base2);
}
#if !COREFX
#if !NETCOREAPP1_0
[Fact]
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);
Assert.Equal(2, dt.Columns.Count);
Assert.Equal("three", dt.Columns[0].ColumnName);
Assert.Equal("four", dt.Columns[1].ColumnName);
Assert.Equal(1, dt.Rows.Count);
Assert.Equal(3, (int)dt.Rows[0][0]);
Assert.Equal(4, (int)dt.Rows[0][1]);
}
#endif
......@@ -535,12 +546,12 @@ public void TestDbString()
e = new DbString { Value = "abcde", IsAnsi = true },
f = new DbString { Value = "abcde", IsAnsi = false },
}).First();
((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);
Assert.Equal(10, (int)obj.a);
Assert.Equal(20, (int)obj.b);
Assert.Equal(5, (int)obj.c);
Assert.Equal(10, (int)obj.d);
Assert.Equal(5, (int)obj.e);
Assert.Equal(10, (int)obj.f);
}
[Fact]
......@@ -552,8 +563,8 @@ public void TestDefaultDbStringDbType()
DbString.IsAnsiDefault = true;
var a = new DbString { Value = "abcde" };
var b = new DbString { Value = "abcde", IsAnsi = false };
a.IsAnsi.IsTrue();
b.IsAnsi.IsFalse();
Assert.True(a.IsAnsi);
Assert.False(b.IsAnsi);
}
finally
{
......@@ -565,16 +576,16 @@ public void TestDefaultDbStringDbType()
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");
Assert.Equal(1, row["A"]);
Assert.Equal("two", row["B"]);
}
[Fact]
public void TestDapperSetsPrivates()
{
connection.Query<PrivateDan>("select 'one' ShadowInDB").First().Shadow.IsEqualTo(1);
Assert.Equal(1, connection.Query<PrivateDan>("select 'one' ShadowInDB").First().Shadow);
connection.QueryFirstOrDefault<PrivateDan>("select 'one' ShadowInDB").Shadow.IsEqualTo(1);
Assert.Equal(1, connection.QueryFirstOrDefault<PrivateDan>("select 'one' ShadowInDB").Shadow);
}
private class PrivateDan
......@@ -598,7 +609,7 @@ public void TestUnexpectedDataMessage()
{
msg = ex.Message;
}
msg.IsEqualTo("The member Foo of type System.GenericUriParser cannot be used as a parameter value");
Assert.Equal("The member Foo of type System.GenericUriParser cannot be used as a parameter value", msg);
}
[Fact]
......@@ -606,7 +617,7 @@ public void TestUnexpectedButFilteredDataMessage()
{
int i = connection.Query<int>("select @Bar", new WithBizarreData { Foo = new GenericUriParser(GenericUriParserOptions.Default), Bar = 23 }).Single();
i.IsEqualTo(23);
Assert.Equal(23, i);
}
private class WithBizarreData
......@@ -627,11 +638,11 @@ public void TestCharInputAndOutput()
const char test = '〠';
char c = connection.Query<char>("select @c", new { c = test }).Single();
c.IsEqualTo(test);
Assert.Equal(c, test);
var obj = connection.Query<WithCharValue>("select @Value as Value", new WithCharValue { Value = c }).Single();
obj.Value.IsEqualTo(test);
Assert.Equal(obj.Value, test);
}
[Fact]
......@@ -640,11 +651,11 @@ public void TestNullableCharInputAndOutputNonNull()
char? test = '〠';
char? c = connection.Query<char?>("select @c", new { c = test }).Single();
c.IsEqualTo(test);
Assert.Equal(c, test);
var obj = connection.Query<WithCharValue>("select @ValueNullable as ValueNullable", new WithCharValue { ValueNullable = c }).Single();
obj.ValueNullable.IsEqualTo(test);
Assert.Equal(obj.ValueNullable, test);
}
[Fact]
......@@ -653,11 +664,11 @@ public void TestNullableCharInputAndOutputNull()
char? test = null;
char? c = connection.Query<char?>("select @c", new { c = test }).Single();
c.IsEqualTo(test);
Assert.Equal(c, test);
var obj = connection.Query<WithCharValue>("select @ValueNullable as ValueNullable", new WithCharValue { ValueNullable = c }).Single();
obj.ValueNullable.IsEqualTo(test);
Assert.Equal(obj.ValueNullable, test);
}
[Fact]
......@@ -675,61 +686,61 @@ private struct CanHazInt
[Fact]
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);
Assert.Equal(connection.Query<short>("select cast(42 as smallint)").Single(), (short)42);
Assert.Equal(connection.Query<short?>("select cast(42 as smallint)").Single(), (short?)42);
Assert.Equal(connection.Query<short?>("select cast(null as smallint)").Single(), (short?)null);
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);
Assert.Equal(connection.Query<ShortEnum>("select cast(42 as smallint)").Single(), (ShortEnum)42);
Assert.Equal(connection.Query<ShortEnum?>("select cast(42 as smallint)").Single(), (ShortEnum?)42);
Assert.Equal(connection.Query<ShortEnum?>("select cast(null as smallint)").Single(), (ShortEnum?)null);
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);
Assert.Equal(row.NonNullableInt16, (short)1);
Assert.Equal(row.NullableInt16, (short)2);
Assert.Equal(ShortEnum.Three, row.NonNullableInt16Enum);
Assert.Equal(ShortEnum.Four, row.NullableInt16Enum);
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);
Assert.Equal(row.NonNullableInt16, (short)5);
Assert.Equal(row.NullableInt16, (short?)null);
Assert.Equal(ShortEnum.Six, row.NonNullableInt16Enum);
Assert.Equal(row.NullableInt16Enum, (ShortEnum?)null);
}
[Fact]
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);
Assert.Equal(connection.Query<int>("select cast(42 as int)").Single(), (int)42);
Assert.Equal(connection.Query<int?>("select cast(42 as int)").Single(), (int?)42);
Assert.Equal(connection.Query<int?>("select cast(null as int)").Single(), (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);
Assert.Equal(connection.Query<IntEnum>("select cast(42 as int)").Single(), (IntEnum)42);
Assert.Equal(connection.Query<IntEnum?>("select cast(42 as int)").Single(), (IntEnum?)42);
Assert.Equal(connection.Query<IntEnum?>("select cast(null as int)").Single(), (IntEnum?)null);
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);
Assert.Equal(row.NonNullableInt32, (int)1);
Assert.Equal(row.NullableInt32, (int)2);
Assert.Equal(IntEnum.Three, row.NonNullableInt32Enum);
Assert.Equal(IntEnum.Four, row.NullableInt32Enum);
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);
Assert.Equal(row.NonNullableInt32, (int)5);
Assert.Equal(row.NullableInt32, (int?)null);
Assert.Equal(IntEnum.Six, row.NonNullableInt32Enum);
Assert.Equal(row.NullableInt32Enum, (IntEnum?)null);
}
public class WithInt16Values
......@@ -757,10 +768,10 @@ public enum IntEnum : int
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");
Assert.True(user.Active);
Assert.Equal(1, user.UserID);
Assert.Equal("abc", user.Email);
Assert.Equal("changeme", user.Password);
}
public class Issue40_User
......@@ -782,7 +793,7 @@ public void ExecuteFromClosed()
using (var conn = GetClosedConnection())
{
conn.Execute("-- nop");
conn.State.IsEqualTo(ConnectionState.Closed);
Assert.Equal(ConnectionState.Closed, conn.State);
}
}
......@@ -791,15 +802,8 @@ 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);
}
var ex = Assert.ThrowsAny<Exception>(() => conn.Execute("nop"));
Assert.Equal(ConnectionState.Closed, conn.State);
}
}
......@@ -809,8 +813,8 @@ public void QueryFromClosed()
using (var conn = GetClosedConnection())
{
var i = conn.Query<int>("select 1").Single();
conn.State.IsEqualTo(ConnectionState.Closed);
i.IsEqualTo(1);
Assert.Equal(ConnectionState.Closed, conn.State);
Assert.Equal(1, i);
}
}
......@@ -819,15 +823,8 @@ 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);
}
Assert.ThrowsAny<Exception>(() => conn.Query<int>("select gibberish").Single());
Assert.Equal(ConnectionState.Closed, conn.State);
}
}
......@@ -835,23 +832,23 @@ public void QueryInvalidFromClosed()
public void TestDynamicMutation()
{
var obj = connection.Query("select 1 as [a], 2 as [b], 3 as [c]").Single();
((int)obj.a).IsEqualTo(1);
Assert.Equal(1, (int)obj.a);
IDictionary<string, object> dict = obj;
Assert.Equals(3, dict.Count);
Assert.IsTrue(dict.Remove("a"));
Assert.IsFalse(dict.Remove("d"));
Assert.Equals(2, dict.Count);
Assert.Equal(3, dict.Count);
Assert.True(dict.Remove("a"));
Assert.False(dict.Remove("d"));
Assert.Equal(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.Equal(3, dict.Count);
Assert.Equal("b,c,d", string.Join(",", dict.Keys.OrderBy(x => x)));
Assert.Equal("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);
Assert.Equal(2, (int)obj.b);
Assert.Equal(3, (int)obj.c);
Assert.Equal(4, (int)obj.d);
try
{
((int)obj.a).IsEqualTo(1);
Assert.Equal(1, (int)obj.a);
throw new InvalidOperationException("should have thrown");
}
catch (RuntimeBinderException)
......@@ -871,10 +868,10 @@ public void TestIssue131()
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);
Assert.True(asDict.ContainsKey("Id"));
Assert.True(asDict.ContainsKey("Title"));
Assert.True(asDict.ContainsKey("Surname"));
Assert.False(asDict.ContainsKey("AddressCount"));
}
// see https://stackoverflow.com/questions/13127886/dapper-returns-null-for-singleordefaultdatediff
......@@ -884,12 +881,12 @@ 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);
Assert.Equal(20, result);
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
Assert.Equal(0, result); // zero rows; default of int over zero rows is zero
}
[Fact]
......@@ -902,13 +899,13 @@ public void TestDapperTableMetadataRetrieval()
// - 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>());
Assert.Equal(Enumerable.Empty<dynamic>(), connection.Query("SELECT value FROM #sut"));
connection.Execute("INSERT INTO #sut (value) VALUES ('test')").IsEqualTo(1);
Assert.Equal(1, connection.Execute("INSERT INTO #sut (value) VALUES ('test')"));
var result = connection.Query("SELECT value FROM #sut");
var first = result.First();
((string)first.value).IsEqualTo("test");
Assert.Equal("test", (string)first.value);
}
[Fact]
......@@ -918,8 +915,8 @@ public void DbStringAnsi()
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);
Assert.Equal(3, a);
Assert.Equal(6, b);
}
private class HasInt32
......@@ -933,10 +930,10 @@ 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);
Assert.Equal(42, i);
i = connection.Query<int>(sql).Single();
Assert.IsEqualTo(42, i);
Assert.Equal(42, i);
}
[Fact]
......@@ -946,11 +943,11 @@ public void TypeBasedViaDynamic()
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);
Assert.Equal(((object)actual).GetType(), type);
int a = actual.A;
string b = actual.B;
a.IsEqualTo(123);
b.IsEqualTo("abc");
Assert.Equal(123, a);
Assert.Equal("abc", b);
}
[Fact]
......@@ -959,11 +956,11 @@ public void TypeBasedViaType()
Type type = Common.GetSomeType();
dynamic actual = connection.Query(type, "select @A as [A], @B as [B]", new { A = 123, B = "abc" }).FirstOrDefault();
((object)actual).GetType().IsEqualTo(type);
Assert.Equal(((object)actual).GetType(), type);
int a = actual.A;
string b = actual.B;
a.IsEqualTo(123);
b.IsEqualTo("abc");
Assert.Equal(123, a);
Assert.Equal("abc", b);
}
private T CheetViaDynamic<T>(T template, string query, object args)
......@@ -975,29 +972,29 @@ private T CheetViaDynamic<T>(T template, string query, object args)
public void Issue22_ExecuteScalar()
{
int i = connection.ExecuteScalar<int>("select 123");
i.IsEqualTo(123);
Assert.Equal(123, i);
i = connection.ExecuteScalar<int>("select cast(123 as bigint)");
i.IsEqualTo(123);
Assert.Equal(123, i);
long j = connection.ExecuteScalar<long>("select 123");
j.IsEqualTo(123L);
Assert.Equal(123L, j);
j = connection.ExecuteScalar<long>("select cast(123 as bigint)");
j.IsEqualTo(123L);
Assert.Equal(123L, j);
int? k = connection.ExecuteScalar<int?>("select @i", new { i = default(int?) });
k.IsNull();
Assert.Null(k);
}
[Fact]
public void Issue142_FailsNamedStatus()
{
var row1 = connection.Query<Issue142_Status>("select @Status as [Status]", new { Status = StatusType.Started }).Single();
row1.Status.IsEqualTo(StatusType.Started);
Assert.Equal(StatusType.Started, row1.Status);
var row2 = connection.Query<Issue142_StatusType>("select @Status as [Status]", new { Status = Status.Started }).Single();
row2.Status.IsEqualTo(Status.Started);
Assert.Equal(Status.Started, row2.Status);
}
public class Issue142_Status
......@@ -1023,7 +1020,7 @@ public enum Status : byte
[Fact]
public void Issue178_SqlServer()
{
const string sql = @"select count(*) from Issue178";
const string sql = "select count(*) from Issue178";
try { connection.Execute("drop table Issue178"); }
catch { /* don't care */ }
try { connection.Execute("create table Issue178(id int not null)"); }
......@@ -1032,19 +1029,19 @@ public void Issue178_SqlServer()
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());
Assert.True(reader1.Read());
Assert.Equal(0, reader1.GetInt32(0));
Assert.False(reader1.Read());
Assert.False(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());
Assert.True(reader2.Read());
Assert.Equal(0, reader2.GetInt32(0));
Assert.False(reader2.Read());
Assert.False(reader2.NextResult());
}
}
......@@ -1052,14 +1049,14 @@ public void Issue178_SqlServer()
public void QueryBasicWithoutQuery()
{
int? i = connection.Query<int?>("print 'not a query'").FirstOrDefault();
i.IsNull();
Assert.Null(i);
}
[Fact]
public void QueryComplexWithoutQuery()
{
var obj = connection.Query<Foo1>("print 'not a query'").FirstOrDefault();
obj.IsNull();
Assert.Null(obj);
}
[FactLongRunning]
......@@ -1068,15 +1065,15 @@ 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);
Assert.Equal(42, i);
var minutes = watch.ElapsedMilliseconds / 1000 / 60;
Assert.IsTrue(minutes >= 0.95 && minutes <= 1.05);
Assert.True(minutes >= 0.95 && minutes <= 1.05);
}
[Fact]
public void SO30435185_InvalidTypeOwner()
{
try
var ex = Assert.Throws<InvalidOperationException>(() =>
{
const string sql = @" INSERT INTO #XXX
(XXXId, AnotherId, ThirdId, Value, Comment)
......@@ -1103,14 +1100,9 @@ public void SO30435185_InvalidTypeOwner()
.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");
}
Assert.Equal(1, rowcount);
});
Assert.Equal("An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context", ex.Message);
}
[Fact]
......@@ -1127,17 +1119,17 @@ public async void SO35470588_WrongValuePidValue()
.ToDictionary(x => x.Pid);
// check the number of rows
rows.Count.IsEqualTo(2);
Assert.Equal(2, rows.Count);
// check row 1
var row = rows[1];
row.Pid.IsEqualTo(1);
row.Value.IsEqualTo(2);
Assert.Equal(1, row.Pid);
Assert.Equal(2, row.Value);
// check row 2
row = rows[2];
row.Pid.IsEqualTo(2);
row.Value.IsEqualTo(568);
Assert.Equal(2, row.Pid);
Assert.Equal(568, row.Value);
}
public class TPTable
......@@ -1150,8 +1142,8 @@ public class TPTable
public void GetOnlyProperties()
{
var obj = connection.QuerySingle<HazGetOnly>("select 42 as [Id], 'def' as [Name];");
obj.Id.IsEqualTo(42);
obj.Name.IsEqualTo("def");
Assert.Equal(42, obj.Id);
Assert.Equal("def", obj.Name);
}
private class HazGetOnly
......
......@@ -12,7 +12,7 @@ public class MultiMapTests : TestBase
public void ParentChildIdentityAssociations()
{
var lookup = new Dictionary<int, Parent>();
var parents = connection.Query<Parent, Child, Parent>(@"select 1 as [Id], 1 as [Id] union all select 1,2 union all select 2,3 union all select 1,4 union all select 3,5",
var parents = connection.Query<Parent, Child, Parent>("select 1 as [Id], 1 as [Id] union all select 1,2 union all select 2,3 union all select 1,4 union all select 3,5",
(parent, child) =>
{
if (!lookup.TryGetValue(parent.Id, out Parent found))
......@@ -22,10 +22,10 @@ public void ParentChildIdentityAssociations()
found.Children.Add(child);
return found;
}).Distinct().ToDictionary(p => p.Id);
parents.Count.IsEqualTo(3);
parents[1].Children.Select(c => c.Id).SequenceEqual(new[] { 1, 2, 4 }).IsTrue();
parents[2].Children.Select(c => c.Id).SequenceEqual(new[] { 3 }).IsTrue();
parents[3].Children.Select(c => c.Id).SequenceEqual(new[] { 5 }).IsTrue();
Assert.Equal(3, parents.Count);
Assert.True(parents[1].Children.Select(c => c.Id).SequenceEqual(new[] { 1, 2, 4 }));
Assert.True(parents[2].Children.Select(c => c.Id).SequenceEqual(new[] { 3 }));
Assert.True(parents[3].Children.Select(c => c.Id).SequenceEqual(new[] { 5 }));
}
private class Parent
......@@ -64,12 +64,12 @@ public void TestMultiMap()
var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post; }).ToList();
var p = data[0];
p.Content.IsEqualTo("Sams Post1");
p.Id.IsEqualTo(1);
p.Owner.Name.IsEqualTo("Sam");
p.Owner.Id.IsEqualTo(99);
Assert.Equal("Sams Post1", p.Content);
Assert.Equal(1, p.Id);
Assert.Equal("Sam", p.Owner.Name);
Assert.Equal(99, p.Owner.Id);
data[2].Owner.IsNull();
Assert.Null(data[2].Owner);
}
finally
{
......@@ -85,18 +85,18 @@ public void TestSchemaChangedMultiMap()
{
var tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", Tuple.Create, splitOn: "Age").Single();
tuple.Item1.Name.IsEqualTo("Alf");
tuple.Item1.Age.IsEqualTo(1);
tuple.Item2.Name.IsEqualTo("Alf");
tuple.Item2.Age.IsEqualTo(1);
Assert.Equal("Alf", tuple.Item1.Name);
Assert.Equal(1, tuple.Item1.Age);
Assert.Equal("Alf", tuple.Item2.Name);
Assert.Equal(1, tuple.Item2.Age);
connection.Execute("alter table #dog drop column Name");
tuple = connection.Query<Dog, Dog, Tuple<Dog, Dog>>("select * from #dog d1 join #dog d2 on 1=1", Tuple.Create, splitOn: "Age").Single();
tuple.Item1.Name.IsNull();
tuple.Item1.Age.IsEqualTo(1);
tuple.Item2.Name.IsNull();
tuple.Item2.Age.IsEqualTo(1);
Assert.Null(tuple.Item1.Name);
Assert.Equal(1, tuple.Item1.Age);
Assert.Null(tuple.Item2.Name);
Assert.Equal(1, tuple.Item2.Age);
}
finally
{
......@@ -107,9 +107,10 @@ public void TestSchemaChangedMultiMap()
[Fact]
public void TestReadMultipleIntegersWithSplitOnAny()
{
connection.Query<int, int, int, Tuple<int, int, int>>(
"select 1,2,3 union all select 4,5,6", Tuple.Create, splitOn: "*")
.IsSequenceEqualTo(new[] { Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6) });
Assert.Equal(
new[] { Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6) },
connection.Query<int, int, int, Tuple<int, int, int>>("select 1,2,3 union all select 4,5,6", Tuple.Create, splitOn: "*")
);
}
private class Multi1
......@@ -127,10 +128,10 @@ public void QueryMultimapFromClosed()
{
using (var conn = GetClosedConnection())
{
conn.State.IsEqualTo(ConnectionState.Closed);
Assert.Equal(ConnectionState.Closed, conn.State);
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);
Assert.Equal(ConnectionState.Closed, conn.State);
Assert.Equal(5, i);
}
}
......@@ -167,8 +168,8 @@ public void TestMultiMapThreeTypesWithGridReader()
var post2 = grid.Read<Post, User, Comment, Post>((post, user, comment) => { post.Owner = user; post.Comment = comment; return post; }).SingleOrDefault();
post2.Comment.Id.IsEqualTo(1);
post2.Owner.Id.IsEqualTo(99);
Assert.Equal(1, post2.Comment.Id);
Assert.Equal(99, post2.Owner.Id);
}
finally
{
......@@ -181,10 +182,10 @@ public void TestMultiMapperIsNotConfusedWithUnorderedCols()
{
var result = connection.Query<Foo1, Bar1, Tuple<Foo1, Bar1>>("select 1 as Id, 2 as BarId, 3 as BarId, 'a' as Name", Tuple.Create, splitOn: "BarId").First();
result.Item1.Id.IsEqualTo(1);
result.Item1.BarId.IsEqualTo(2);
result.Item2.BarId.IsEqualTo(3);
result.Item2.Name.IsEqualTo("a");
Assert.Equal(1, result.Item1.Id);
Assert.Equal(2, result.Item1.BarId);
Assert.Equal(3, result.Item2.BarId);
Assert.Equal("a", result.Item2.Name);
}
[Fact]
......@@ -212,12 +213,12 @@ public void TestMultiMapDynamic()
var p = data[0];
// hairy extension method support for dynamics
((string)p.Content).IsEqualTo("Sams Post1");
((int)p.Id).IsEqualTo(1);
((string)p.Owner.Name).IsEqualTo("Sam");
((int)p.Owner.Id).IsEqualTo(99);
Assert.Equal("Sams Post1", (string)p.Content);
Assert.Equal(1, (int)p.Id);
Assert.Equal("Sam", (string)p.Owner.Name);
Assert.Equal(99, (int)p.Owner.Id);
((object)data[2].Owner).IsNull();
Assert.Null((object)data[2].Owner);
connection.Execute("drop table #Users drop table #Posts");
}
......@@ -225,65 +226,65 @@ public void TestMultiMapDynamic()
[Fact]
public void TestMultiMapWithSplit() // https://stackoverflow.com/q/6056778/23354
{
const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name";
const string sql = "select 1 as id, 'abc' as name, 2 as id, 'def' as name";
var product = connection.Query<Product, Category, Product>(sql, (prod, cat) =>
{
prod.Category = cat;
return prod;
}).First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.Id.IsEqualTo(2);
product.Category.Name.IsEqualTo("def");
Assert.Equal(1, product.Id);
Assert.Equal("abc", product.Name);
Assert.Equal(2, product.Category.Id);
Assert.Equal("def", product.Category.Name);
}
[Fact]
public void TestMultiMapWithSplitWithNullValue() // https://stackoverflow.com/q/10744728/449906
{
const string sql = @"select 1 as id, 'abc' as name, NULL as description, 'def' as name";
const string sql = "select 1 as id, 'abc' as name, NULL as description, 'def' as name";
var product = connection.Query<Product, Category, Product>(sql, (prod, cat) =>
{
prod.Category = cat;
return prod;
}, splitOn: "description").First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.IsNull();
Assert.Equal(1, product.Id);
Assert.Equal("abc", product.Name);
Assert.Null(product.Category);
}
[Fact]
public void TestMultiMapWithSplitWithNullValueAndSpoofColumn() // https://stackoverflow.com/q/10744728/449906
{
const string sql = @"select 1 as id, 'abc' as name, 1 as spoof, NULL as description, 'def' as name";
const string sql = "select 1 as id, 'abc' as name, 1 as spoof, NULL as description, 'def' as name";
var product = connection.Query<Product, Category, Product>(sql, (prod, cat) =>
{
prod.Category = cat;
return prod;
}, splitOn: "spoof").First();
// assertions
product.Id.IsEqualTo(1);
product.Name.IsEqualTo("abc");
product.Category.IsNotNull();
product.Category.Id.IsEqualTo(0);
product.Category.Name.IsEqualTo("def");
product.Category.Description.IsNull();
Assert.Equal(1, product.Id);
Assert.Equal("abc", product.Name);
Assert.NotNull(product.Category);
Assert.Equal(0, product.Category.Id);
Assert.Equal("def", product.Category.Name);
Assert.Null(product.Category.Description);
}
[Fact]
public void TestMultiMappingVariations()
{
const string sql = @"select 1 as Id, 'a' as Content, 2 as Id, 'b' as Content, 3 as Id, 'c' as Content, 4 as Id, 'd' as Content, 5 as Id, 'e' as Content";
const string sql = "select 1 as Id, 'a' as Content, 2 as Id, 'b' as Content, 3 as Id, 'c' as Content, 4 as Id, 'd' as Content, 5 as Id, 'e' as Content";
var order = connection.Query<dynamic, dynamic, dynamic, dynamic>(sql, (o, owner, creator) => { o.Owner = owner; o.Creator = creator; return o; }).First();
Assert.IsEqualTo(order.Id, 1);
Assert.IsEqualTo(order.Content, "a");
Assert.IsEqualTo(order.Owner.Id, 2);
Assert.IsEqualTo(order.Owner.Content, "b");
Assert.IsEqualTo(order.Creator.Id, 3);
Assert.IsEqualTo(order.Creator.Content, "c");
Assert.Equal(order.Id, 1);
Assert.Equal(order.Content, "a");
Assert.Equal(order.Owner.Id, 2);
Assert.Equal(order.Owner.Content, "b");
Assert.Equal(order.Creator.Id, 3);
Assert.Equal(order.Creator.Content, "c");
order = connection.Query<dynamic, dynamic, dynamic, dynamic, dynamic>(sql, (o, owner, creator, address) =>
{
......@@ -293,27 +294,27 @@ public void TestMultiMappingVariations()
return o;
}).First();
Assert.IsEqualTo(order.Id, 1);
Assert.IsEqualTo(order.Content, "a");
Assert.IsEqualTo(order.Owner.Id, 2);
Assert.IsEqualTo(order.Owner.Content, "b");
Assert.IsEqualTo(order.Creator.Id, 3);
Assert.IsEqualTo(order.Creator.Content, "c");
Assert.IsEqualTo(order.Owner.Address.Id, 4);
Assert.IsEqualTo(order.Owner.Address.Content, "d");
Assert.Equal(order.Id, 1);
Assert.Equal(order.Content, "a");
Assert.Equal(order.Owner.Id, 2);
Assert.Equal(order.Owner.Content, "b");
Assert.Equal(order.Creator.Id, 3);
Assert.Equal(order.Creator.Content, "c");
Assert.Equal(order.Owner.Address.Id, 4);
Assert.Equal(order.Owner.Address.Content, "d");
order = connection.Query<dynamic, dynamic, dynamic, dynamic, dynamic, dynamic>(sql, (a, b, c, d, e) => { a.B = b; a.C = c; a.C.D = d; a.E = e; return a; }).First();
Assert.IsEqualTo(order.Id, 1);
Assert.IsEqualTo(order.Content, "a");
Assert.IsEqualTo(order.B.Id, 2);
Assert.IsEqualTo(order.B.Content, "b");
Assert.IsEqualTo(order.C.Id, 3);
Assert.IsEqualTo(order.C.Content, "c");
Assert.IsEqualTo(order.C.D.Id, 4);
Assert.IsEqualTo(order.C.D.Content, "d");
Assert.IsEqualTo(order.E.Id, 5);
Assert.IsEqualTo(order.E.Content, "e");
Assert.Equal(order.Id, 1);
Assert.Equal(order.Content, "a");
Assert.Equal(order.B.Id, 2);
Assert.Equal(order.B.Content, "b");
Assert.Equal(order.C.Id, 3);
Assert.Equal(order.C.Content, "c");
Assert.Equal(order.C.D.Id, 4);
Assert.Equal(order.C.D.Content, "d");
Assert.Equal(order.E.Id, 5);
Assert.Equal(order.E.Content, "e");
}
private class UserWithConstructor
......@@ -364,12 +365,12 @@ public void TestMultiMapWithConstructor()
PostWithConstructor[] data = connection.Query<PostWithConstructor, UserWithConstructor, PostWithConstructor>(sql, (post, user) => { post.Owner = user; return post; }).ToArray();
var p = data.First();
p.FullContent.IsEqualTo("Sams Post1");
p.Ident.IsEqualTo(1);
p.Owner.FullName.IsEqualTo("Sam");
p.Owner.Ident.IsEqualTo(99);
Assert.Equal("Sams Post1", p.FullContent);
Assert.Equal(1, p.Ident);
Assert.Equal("Sam", p.Owner.FullName);
Assert.Equal(99, p.Owner.Ident);
data[2].Owner.IsNull();
Assert.Null(data[2].Owner);
}
finally
{
......@@ -436,26 +437,26 @@ public void TestMultiMapArbitraryMaps()
var data = connection.Query<ReviewBoard>(sql, types, mapper).ToList();
var p = data[0];
p.Id.IsEqualTo(1);
p.Name.IsEqualTo("Review Board 1");
p.User1.Id.IsEqualTo(1);
p.User2.Id.IsEqualTo(2);
p.User3.Id.IsEqualTo(3);
p.User4.Id.IsEqualTo(4);
p.User5.Id.IsEqualTo(5);
p.User6.Id.IsEqualTo(6);
p.User7.Id.IsEqualTo(7);
p.User8.Id.IsEqualTo(8);
p.User9.Id.IsEqualTo(9);
p.User1.Name.IsEqualTo("User 1");
p.User2.Name.IsEqualTo("User 2");
p.User3.Name.IsEqualTo("User 3");
p.User4.Name.IsEqualTo("User 4");
p.User5.Name.IsEqualTo("User 5");
p.User6.Name.IsEqualTo("User 6");
p.User7.Name.IsEqualTo("User 7");
p.User8.Name.IsEqualTo("User 8");
p.User9.Name.IsEqualTo("User 9");
Assert.Equal(1, p.Id);
Assert.Equal("Review Board 1", p.Name);
Assert.Equal(1, p.User1.Id);
Assert.Equal(2, p.User2.Id);
Assert.Equal(3, p.User3.Id);
Assert.Equal(4, p.User4.Id);
Assert.Equal(5, p.User5.Id);
Assert.Equal(6, p.User6.Id);
Assert.Equal(7, p.User7.Id);
Assert.Equal(8, p.User8.Id);
Assert.Equal(9, p.User9.Id);
Assert.Equal("User 1", p.User1.Name);
Assert.Equal("User 2", p.User2.Name);
Assert.Equal("User 3", p.User3.Name);
Assert.Equal("User 4", p.User4.Name);
Assert.Equal("User 5", p.User5.Name);
Assert.Equal("User 6", p.User6.Name);
Assert.Equal("User 7", p.User7.Name);
Assert.Equal("User 8", p.User8.Name);
Assert.Equal("User 9", p.User9.Name);
}
finally
{
......@@ -496,12 +497,12 @@ public void TestMultiMapGridReader()
var data = grid.Read<Post, User, Post>((post, user) => { post.Owner = user; return post; }).ToList();
var p = data[0];
p.Content.IsEqualTo("Sams Post1");
p.Id.IsEqualTo(1);
p.Owner.Name.IsEqualTo("Sam" + i);
p.Owner.Id.IsEqualTo(99);
Assert.Equal("Sams Post1", p.Content);
Assert.Equal(1, p.Id);
Assert.Equal(p.Owner.Name, "Sam" + i);
Assert.Equal(99, p.Owner.Id);
data[2].Owner.IsNull();
Assert.Null(data[2].Owner);
}
connection.Execute("drop table #Users drop table #Posts");
......@@ -519,13 +520,13 @@ public void TestFlexibleMultiMapping()
var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>>
(sql, Tuple.Create, splitOn: "AddressId,Id").First();
personWithAddress.Item1.PersonId.IsEqualTo(1);
personWithAddress.Item1.Name.IsEqualTo("bob");
personWithAddress.Item2.AddressId.IsEqualTo(2);
personWithAddress.Item2.Name.IsEqualTo("abc street");
personWithAddress.Item2.PersonId.IsEqualTo(1);
personWithAddress.Item3.Id.IsEqualTo(3);
personWithAddress.Item3.Name.IsEqualTo("fred");
Assert.Equal(1, personWithAddress.Item1.PersonId);
Assert.Equal("bob", personWithAddress.Item1.Name);
Assert.Equal(2, personWithAddress.Item2.AddressId);
Assert.Equal("abc street", personWithAddress.Item2.Name);
Assert.Equal(1, personWithAddress.Item2.PersonId);
Assert.Equal(3, personWithAddress.Item3.Id);
Assert.Equal("fred", personWithAddress.Item3.Name);
}
[Fact]
......@@ -539,13 +540,13 @@ public void TestMultiMappingWithSplitOnSpaceBetweenCommas()
var personWithAddress = connection.Query<Person, Address, Extra, Tuple<Person, Address, Extra>>
(sql, Tuple.Create, splitOn: "AddressId, Id").First();
personWithAddress.Item1.PersonId.IsEqualTo(1);
personWithAddress.Item1.Name.IsEqualTo("bob");
personWithAddress.Item2.AddressId.IsEqualTo(2);
personWithAddress.Item2.Name.IsEqualTo("abc street");
personWithAddress.Item2.PersonId.IsEqualTo(1);
personWithAddress.Item3.Id.IsEqualTo(3);
personWithAddress.Item3.Name.IsEqualTo("fred");
Assert.Equal(1, personWithAddress.Item1.PersonId);
Assert.Equal("bob", personWithAddress.Item1.Name);
Assert.Equal(2, personWithAddress.Item2.AddressId);
Assert.Equal("abc street", personWithAddress.Item2.Name);
Assert.Equal(1, personWithAddress.Item2.PersonId);
Assert.Equal(3, personWithAddress.Item3.Id);
Assert.Equal("fred", personWithAddress.Item3.Name);
}
private class Extra
......@@ -567,10 +568,10 @@ public void TestMultiMappingWithNonReturnedProperty()
return p;
}, splitOn: "BlogId").First();
postWithBlog.PostId.IsEqualTo(1);
postWithBlog.Title.IsEqualTo("Title");
postWithBlog.Blog.BlogId.IsEqualTo(2);
postWithBlog.Blog.Title.IsEqualTo("Blog");
Assert.Equal(1, postWithBlog.PostId);
Assert.Equal("Title", postWithBlog.Title);
Assert.Equal(2, postWithBlog.Blog.BlogId);
Assert.Equal("Blog", postWithBlog.Blog.Title);
}
private class Post_DupeProp
......@@ -601,13 +602,13 @@ public void TestSplitWithMissingMembers()
result.ID.Equals(123);
result.Title.Equals("abc");
result.CreateDate.Equals(new DateTime(2013, 2, 1));
result.Name.IsNull();
result.Content.IsNull();
Assert.Null(result.Name);
Assert.Null(result.Content);
result.Author.Phone.Equals("def");
result.Author.Name.Equals("ghi");
result.Author.ID.Equals(0);
result.Author.Address.IsNull();
Assert.Null(result.Author.Address);
}
public class Profile
......
......@@ -2,6 +2,7 @@
using System.Linq;
namespace Dapper.Tests
{
[Collection(NonParallelDefinition.Name)]
public class NullTests : TestBase
{
[Fact]
......@@ -33,30 +34,30 @@ private void TestNullable(bool applyNulls)
var obj = data[2];
obj.Id.IsEqualTo(2);
obj.A.IsEqualTo(42);
obj.B.IsEqualTo(42);
obj.C.IsEqualTo("abc");
obj.D.IsEqualTo(AnEnum.A);
obj.E.IsEqualTo(AnEnum.A);
Assert.Equal(2, obj.Id);
Assert.Equal(42, obj.A);
Assert.Equal(42, obj.B);
Assert.Equal("abc", obj.C);
Assert.Equal(AnEnum.A, obj.D);
Assert.Equal(AnEnum.A, obj.E);
obj = data[1];
obj.Id.IsEqualTo(1);
Assert.Equal(1, obj.Id);
if (applyNulls)
{
obj.A.IsEqualTo(2); // cannot be null
obj.B.IsEqualTo(null);
obj.C.IsEqualTo(null);
obj.D.IsEqualTo(AnEnum.B);
obj.E.IsEqualTo(null);
Assert.Equal(2, obj.A); // cannot be null
Assert.Null(obj.B);
Assert.Null(obj.C);
Assert.Equal(AnEnum.B, obj.D);
Assert.Null(obj.E);
}
else
{
obj.A.IsEqualTo(2);
obj.B.IsEqualTo(2);
obj.C.IsEqualTo("def");
obj.D.IsEqualTo(AnEnum.B);
obj.E.IsEqualTo(AnEnum.B);
Assert.Equal(2, obj.A);
Assert.Equal(2, obj.B);
Assert.Equal("def", obj.C);
Assert.Equal(AnEnum.B, obj.D);
Assert.Equal(AnEnum.B, obj.E);
}
} finally
{
......
......@@ -10,6 +10,7 @@
using Xunit;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Diagnostics;
#if ENTITY_FRAMEWORK
using System.Data.Entity.Spatial;
......@@ -37,19 +38,8 @@ void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Id
}
}
private class IntDynamicParam : SqlMapper.IDynamicParameters
{
private readonly IEnumerable<int> numbers;
public IntDynamicParam(IEnumerable<int> numbers)
{
this.numbers = numbers;
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
private static List<Microsoft.SqlServer.Server.SqlDataRecord> CreateSqlDataRecordList(IEnumerable<int> numbers)
{
var sqlCommand = (SqlCommand)command;
sqlCommand.CommandType = CommandType.StoredProcedure;
var number_list = new List<Microsoft.SqlServer.Server.SqlDataRecord>();
// Create an SqlMetaData object that describes our table type.
......@@ -63,6 +53,24 @@ public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
number_list.Add(rec); // Add it to the list.
}
return number_list;
}
private class IntDynamicParam : SqlMapper.IDynamicParameters
{
private readonly IEnumerable<int> numbers;
public IntDynamicParam(IEnumerable<int> numbers)
{
this.numbers = numbers;
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
var sqlCommand = (SqlCommand)command;
sqlCommand.CommandType = CommandType.StoredProcedure;
var number_list = CreateSqlDataRecordList(numbers);
// Add the table parameter.
var p = sqlCommand.Parameters.Add("ints", SqlDbType.Structured);
p.Direction = ParameterDirection.Input;
......@@ -84,18 +92,7 @@ public void AddParameter(IDbCommand command, string name)
var sqlCommand = (SqlCommand)command;
sqlCommand.CommandType = CommandType.StoredProcedure;
var number_list = new List<Microsoft.SqlServer.Server.SqlDataRecord>();
// Create an SqlMetaData object that describes our table type.
Microsoft.SqlServer.Server.SqlMetaData[] tvp_definition = { new Microsoft.SqlServer.Server.SqlMetaData("n", SqlDbType.Int) };
foreach (int n in numbers)
{
// Create a new record, using the metadata array above.
var rec = new Microsoft.SqlServer.Server.SqlDataRecord(tvp_definition);
rec.SetInt32(0, n); // Set the value.
number_list.Add(rec); // Add it to the list.
}
var number_list = CreateSqlDataRecordList(numbers);
// Add the table parameter.
var p = sqlCommand.Parameters.Add(name, SqlDbType.Structured);
......@@ -113,22 +110,20 @@ public void TestMagicParam()
// 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);
Assert.Equal(first.a, 1);
}
* */
[Fact]
public void TestDoubleParam()
{
connection.Query<double>("select @d", new { d = 0.1d }).First()
.IsEqualTo(0.1d);
Assert.Equal(0.1d, connection.Query<double>("select @d", new { d = 0.1d }).First());
}
[Fact]
public void TestBoolParam()
{
connection.Query<bool>("select @b", new { b = false }).First()
.IsFalse();
Assert.False(connection.Query<bool>("select @b", new { b = false }).First());
}
// http://code.google.com/p/dapper-dot-net/issues/detail?id=70
......@@ -137,22 +132,25 @@ public void TestBoolParam()
[Fact]
public void TestTimeSpanParam()
{
connection.Query<TimeSpan>("select @ts", new { ts = TimeSpan.FromMinutes(42) }).First()
.IsEqualTo(TimeSpan.FromMinutes(42));
Assert.Equal(connection.Query<TimeSpan>("select @ts", new { ts = TimeSpan.FromMinutes(42) }).First(), TimeSpan.FromMinutes(42));
}
[Fact]
public void PassInIntArray()
{
Assert.Equal(
new[] { 1, 2, 3 },
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() })
.IsSequenceEqualTo(new[] { 1, 2, 3 });
);
}
[Fact]
public void PassInEmptyIntArray()
{
Assert.Equal(
new int[0],
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]);
);
}
[Fact]
......@@ -160,8 +158,8 @@ public void TestExecuteCommandWithHybridParameters()
{
var p = new DynamicParameters(new { a = 1, b = 2 });
p.Add("c", dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute(@"set @c = @a + @b", p);
p.Get<int>("@c").IsEqualTo(3);
connection.Execute("set @c = @a + @b", p);
Assert.Equal(3, p.Get<int>("@c"));
}
[Fact]
......@@ -213,11 +211,9 @@ public void TestParameterInclusionNotSensitiveToCurrentCulture()
public void TestMassiveStrings()
{
var str = new string('X', 20000);
connection.Query<string>("select @a", new { a = str }).First()
.IsEqualTo(str);
Assert.Equal(connection.Query<string>("select @a", new { a = str }).First(), str);
}
#if !COREFX
[Fact]
public void TestTVPWithAnonymousObject()
{
......@@ -227,10 +223,10 @@ public void TestTVPWithAnonymousObject()
connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers");
var nums = connection.Query<int>("get_ints", new { integers = new IntCustomParam(new int[] { 1, 2, 3 }) }, commandType: CommandType.StoredProcedure).ToList();
nums[0].IsEqualTo(1);
nums[1].IsEqualTo(2);
nums[2].IsEqualTo(3);
nums.Count.IsEqualTo(3);
Assert.Equal(1, nums[0]);
Assert.Equal(2, nums[1]);
Assert.Equal(3, nums[2]);
Assert.Equal(3, nums.Count);
}
finally
{
......@@ -255,10 +251,10 @@ public void TestTVP()
connection.Execute("CREATE PROC get_ints @ints int_list_type READONLY AS select * from @ints");
var nums = connection.Query<int>("get_ints", new IntDynamicParam(new int[] { 1, 2, 3 })).ToList();
nums[0].IsEqualTo(1);
nums[1].IsEqualTo(2);
nums[2].IsEqualTo(3);
nums.Count.IsEqualTo(3);
Assert.Equal(1, nums[0]);
Assert.Equal(2, nums[1]);
Assert.Equal(3, nums[2]);
Assert.Equal(3, nums.Count);
}
finally
{
......@@ -288,18 +284,7 @@ public new void AddParameters(IDbCommand command, SqlMapper.Identity identity)
var sqlCommand = (SqlCommand)command;
sqlCommand.CommandType = CommandType.StoredProcedure;
var number_list = new List<Microsoft.SqlServer.Server.SqlDataRecord>();
// Create an SqlMetaData object that describes our table type.
Microsoft.SqlServer.Server.SqlMetaData[] tvp_definition = { new Microsoft.SqlServer.Server.SqlMetaData("n", SqlDbType.Int) };
foreach (int n in numbers)
{
// Create a new record, using the metadata array above.
var rec = new Microsoft.SqlServer.Server.SqlDataRecord(tvp_definition);
rec.SetInt32(0, n); // Set the value.
number_list.Add(rec); // Add it to the list.
}
var number_list = CreateSqlDataRecordList(numbers);
// Add the table parameter.
var p = sqlCommand.Parameters.Add("ints", SqlDbType.Structured);
......@@ -321,13 +306,13 @@ public void TestTVPWithAdditionalParams()
dynamicParameters.AddDynamicParams(new { stringParam = "stringParam", dateParam = new DateTime(2012, 1, 1) });
var results = connection.Query("get_values", dynamicParameters, commandType: CommandType.StoredProcedure).ToList();
results.Count.IsEqualTo(3);
Assert.Equal(3, results.Count);
for (int i = 0; i < results.Count; i++)
{
var result = results[i];
Assert.IsEqualTo(i + 1, result.n);
Assert.IsEqualTo("stringParam", result.stringParam);
Assert.IsEqualTo(new DateTime(2012, 1, 1), result.dateParam);
Assert.Equal(i + 1, result.n);
Assert.Equal("stringParam", result.stringParam);
Assert.Equal(new DateTime(2012, 1, 1), result.dateParam);
}
}
finally
......@@ -343,6 +328,83 @@ public void TestTVPWithAdditionalParams()
}
}
[Fact]
public void TestSqlDataRecordListParametersWithAsTableValuedParameter()
{
try
{
connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)");
connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers");
var records = CreateSqlDataRecordList(new int[] { 1, 2, 3 });
var nums = connection.Query<int>("get_ints", new { integers = records.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).ToList();
Assert.Equal(new int[] { 1, 2, 3 }, nums);
nums = connection.Query<int>("select * from @integers", new { integers = records.AsTableValuedParameter("int_list_type") }).ToList();
Assert.Equal(new int[] { 1, 2, 3 }, nums);
try
{
connection.Query<int>("select * from @integers", new { integers = records.AsTableValuedParameter() }).First();
throw new InvalidOperationException();
}
catch (Exception ex)
{
ex.Message.Equals("The table type parameter 'ids' must have a valid type name.");
}
}
finally
{
try
{
connection.Execute("DROP PROC get_ints");
}
finally
{
connection.Execute("DROP TYPE int_list_type");
}
}
}
[Fact]
public void TestSqlDataRecordListParametersWithTypeHandlers()
{
try
{
connection.Execute("CREATE TYPE int_list_type AS TABLE (n int NOT NULL PRIMARY KEY)");
connection.Execute("CREATE PROC get_ints @integers int_list_type READONLY AS select * from @integers");
// Variable type has to be IEnumerable<SqlDataRecord> for TypeHandler to kick in.
IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> records = CreateSqlDataRecordList(new int[] { 1, 2, 3 });
var nums = connection.Query<int>("get_ints", new { integers = records }, commandType: CommandType.StoredProcedure).ToList();
Assert.Equal(new int[] { 1, 2, 3 }, nums);
try
{
connection.Query<int>("select * from @integers", new { integers = records }).First();
throw new InvalidOperationException();
}
catch (Exception ex)
{
ex.Message.Equals("The table type parameter 'ids' must have a valid type name.");
}
}
finally
{
try
{
connection.Execute("DROP PROC get_ints");
}
finally
{
connection.Execute("DROP TYPE int_list_type");
}
}
}
#if !NETCOREAPP1_0
[Fact]
public void DataTableParameters()
{
......@@ -358,10 +420,10 @@ public void DataTableParameters()
var table = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } };
int count = connection.Query<int>("#DataTableParameters", new { ids = table.AsTableValuedParameter() }, commandType: CommandType.StoredProcedure).First();
count.IsEqualTo(3);
Assert.Equal(3, count);
count = connection.Query<int>("select count(1) from @ids", new { ids = table.AsTableValuedParameter("MyTVPType") }).First();
count.IsEqualTo(3);
Assert.Equal(3, count);
try
{
......@@ -390,10 +452,10 @@ public void SO29533765_DataTableParametersViaDynamicParameters()
["ids"] = table
};
int count = connection.Query<int>("#DataTableParameters", args, commandType: CommandType.StoredProcedure).First();
count.IsEqualTo(3);
Assert.Equal(3, count);
count = connection.Query<int>("select count(1) from @ids", args).First();
count.IsEqualTo(3);
Assert.Equal(3, count);
}
[Fact]
......@@ -414,7 +476,7 @@ public void SO26468710_InWithTVPs()
declare @tmp table(id int not null);
insert @tmp (id) values(1), (2), (3), (4), (5), (6), (7);
select * from @tmp t inner join @ids i on i.id = t.id", new { ids }).Sum();
sum.IsEqualTo(9);
Assert.Equal(9, sum);
}
[Fact]
......@@ -432,10 +494,10 @@ public void DataTableParametersWithExtendedProperty()
var table = new DataTable { Columns = { { "id", typeof(int) } }, Rows = { { 1 }, { 2 }, { 3 } } };
table.SetTypeName("MyTVPType"); // <== extended metadata
int count = connection.Query<int>("#DataTableParameters", new { ids = table }, commandType: CommandType.StoredProcedure).First();
count.IsEqualTo(3);
Assert.Equal(3, count);
count = connection.Query<int>("select count(1) from @ids", new { ids = table }).First();
count.IsEqualTo(3);
Assert.Equal(3, count);
try
{
......@@ -477,7 +539,7 @@ public void SO29596645_TvpProperty()
int val = connection.Query<int>("#SO29596645_Proc", obj.Rules, commandType: CommandType.StoredProcedure).Single();
// 4 + 9 + 7 = 20
val.IsEqualTo(20);
Assert.Equal(20, val);
}
private class SO29596645_RuleTableValuedParameters : SqlMapper.IDynamicParameters
......@@ -491,7 +553,7 @@ public SO29596645_RuleTableValuedParameters(string parameterName)
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
Console.WriteLine("> AddParameters");
Debug.WriteLine("> AddParameters");
var lazy = (SqlCommand)command;
lazy.Parameters.AddWithValue("Id", 7);
var table = new DataTable
......@@ -500,7 +562,7 @@ public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
Rows = { { 4 }, { 9 } }
};
lazy.Parameters.AddWithValue("Rules", table);
Console.WriteLine("< AddParameters");
Debug.WriteLine("< AddParameters");
}
}
......@@ -545,10 +607,10 @@ public void DBGeography_SO24405645_SO24402424()
};
connection.Execute("insert #Geo(id, geo, geometry) values (@Id, @Geo, @Geometry)", obj);
var row = connection.Query<HazGeo>("select * from #Geo where id=1").SingleOrDefault();
row.IsNotNull();
row.Id.IsEqualTo(1);
row.Geo.IsNotNull();
row.Geometry.IsNotNull();
Assert.NotNull(row);
Assert.Equal(1, row.Id);
Assert.NotNull(row.Geo);
Assert.NotNull(row.Geometry);
}
[Fact]
......@@ -565,10 +627,10 @@ public void SqlGeography_SO25538154()
};
connection.Execute("insert #SqlGeo(id, geo, geometry) values (@Id, @Geo, @Geometry)", obj);
var row = connection.Query<HazSqlGeo>("select * from #SqlGeo where id=1").SingleOrDefault();
row.IsNotNull();
row.Id.IsEqualTo(1);
row.Geo.IsNotNull();
row.Geometry.IsNotNull();
Assert.NotNull(row);
Assert.Equal(1, row.Id);
Assert.NotNull(row.Geo);
Assert.NotNull(row.Geometry);
}
[Fact]
......@@ -584,21 +646,21 @@ public void NullableSqlGeometry()
};
connection.Execute("insert #SqlNullableGeo(id, geometry) values (@Id, @Geometry)", obj);
var row = connection.Query<HazSqlGeo>("select * from #SqlNullableGeo where id=1").SingleOrDefault();
row.IsNotNull();
row.Id.IsEqualTo(1);
row.Geometry.IsNull();
Assert.NotNull(row);
Assert.Equal(1, row.Id);
Assert.Null(row.Geometry);
}
[Fact]
public void SqlHierarchyId_SO18888911()
{
Dapper.SqlMapper.ResetTypeHandlers();
SqlMapper.ResetTypeHandlers();
var row = connection.Query<HazSqlHierarchy>("select 3 as [Id], hierarchyid::Parse('/1/2/3/') as [Path]").Single();
row.Id.Equals(3);
row.Path.IsNotNull();
Assert.NotEqual(default(SqlHierarchyId), row.Path);
var val = connection.Query<SqlHierarchyId>("select @Path", row).Single();
val.IsNotNull();
Assert.NotEqual(default(SqlHierarchyId), val);
}
public class HazSqlHierarchy
......@@ -619,8 +681,8 @@ public void TestCustomParameters()
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");
Assert.Equal(123, foo);
Assert.Equal("abc", bar);
}
[Fact]
......@@ -631,7 +693,7 @@ public void TestDynamicParamNullSupport()
p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("select @b = null", p);
p.Get<int?>("@b").IsNull();
Assert.Null(p.Get<int?>("@b"));
}
[Fact]
......@@ -643,10 +705,10 @@ public void TestAppendingAnonClasses()
var result = connection.Query("select @A a,@B b,@C c,@D d", p).Single();
((int)result.a).IsEqualTo(1);
((int)result.b).IsEqualTo(2);
((int)result.c).IsEqualTo(3);
((int)result.d).IsEqualTo(4);
Assert.Equal(1, (int)result.a);
Assert.Equal(2, (int)result.b);
Assert.Equal(3, (int)result.c);
Assert.Equal(4, (int)result.d);
}
[Fact]
......@@ -663,8 +725,8 @@ public void TestAppendingADictionary()
var result = connection.Query("select @A a, @B b", p).Single();
((int)result.a).IsEqualTo(1);
((string)result.b).IsEqualTo("two");
Assert.Equal(1, (int)result.a);
Assert.Equal("two", (string)result.b);
}
[Fact]
......@@ -679,8 +741,8 @@ public void TestAppendingAnExpandoObject()
var result = connection.Query("select @A a, @B b", p).Single();
((int)result.a).IsEqualTo(1);
((string)result.b).IsEqualTo("two");
Assert.Equal(1, (int)result.a);
Assert.Equal("two", (string)result.b);
}
[Fact]
......@@ -692,9 +754,9 @@ public void TestAppendingAList()
var result = connection.Query<int>("select * from (select 1 A union all select 2 union all select 3) X where A in @list", p).ToList();
result[0].IsEqualTo(1);
result[1].IsEqualTo(2);
result[2].IsEqualTo(3);
Assert.Equal(1, result[0]);
Assert.Equal(2, result[1]);
Assert.Equal(3, result[2]);
}
[Fact]
......@@ -707,9 +769,9 @@ public void TestAppendingAListAsDictionary()
var result = connection.Query<int>("select * from (select 1 A union all select 2 union all select 3) X where A in @ids", p).ToList();
result[0].IsEqualTo(1);
result[1].IsEqualTo(2);
result[2].IsEqualTo(3);
Assert.Equal(1, result[0]);
Assert.Equal(2, result[1]);
Assert.Equal(3, result[2]);
}
[Fact]
......@@ -721,9 +783,9 @@ public void TestAppendingAListByName()
var result = connection.Query<int>("select * from (select 1 A union all select 2 union all select 3) X where A in @ids", p).ToList();
result[0].IsEqualTo(1);
result[1].IsEqualTo(2);
result[2].IsEqualTo(3);
Assert.Equal(1, result[0]);
Assert.Equal(2, result[1]);
Assert.Equal(3, result[2]);
}
[Fact]
......@@ -738,13 +800,13 @@ select count(1)
where y.x in @vals
option (optimize for (@vals unKnoWn))";
int count = connection.Query<int>(sql, new { vals = new[] { 1, 2, 3, 4 } }).Single();
count.IsEqualTo(2);
Assert.Equal(2, count);
count = connection.Query<int>(sql, new { vals = new[] { 1 } }).Single();
count.IsEqualTo(1);
Assert.Equal(1, count);
count = connection.Query<int>(sql, new { vals = new int[0] }).Single();
count.IsEqualTo(0);
Assert.Equal(0, count);
}
[Fact]
......@@ -759,7 +821,7 @@ @a TIME
BEGIN
SELECT @a
END");
connection.Query<TimeSpan>("#TestProcWithTimeParameter", p, commandType: CommandType.StoredProcedure).First().IsEqualTo(new TimeSpan(10, 0, 0));
Assert.Equal(connection.Query<TimeSpan>("#TestProcWithTimeParameter", p, commandType: CommandType.StoredProcedure).First(), new TimeSpan(10, 0, 0));
}
[Fact]
......@@ -767,7 +829,7 @@ public void TestUniqueIdentifier()
{
var guid = Guid.NewGuid();
var result = connection.Query<Guid>("declare @foo uniqueidentifier set @foo = @guid select @foo", new { guid }).Single();
result.IsEqualTo(guid);
Assert.Equal(guid, result);
}
[Fact]
......@@ -775,7 +837,7 @@ public void TestNullableUniqueIdentifierNonNull()
{
Guid? guid = Guid.NewGuid();
var result = connection.Query<Guid?>("declare @foo uniqueidentifier set @foo = @guid select @foo", new { guid }).Single();
result.IsEqualTo(guid);
Assert.Equal(guid, result);
}
[Fact]
......@@ -783,7 +845,7 @@ public void TestNullableUniqueIdentifierNull()
{
Guid? guid = null;
var result = connection.Query<Guid?>("declare @foo uniqueidentifier set @foo = @guid select @foo", new { guid }).Single();
result.IsEqualTo(guid);
Assert.Equal(guid, result);
}
[Fact]
......@@ -793,9 +855,8 @@ public void TestSupportForDynamicParameters()
p.Add("name", "bob");
p.Add("age", dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Query<string>("set @age = 11 select @name", p).First().IsEqualTo("bob");
p.Get<int>("age").IsEqualTo(11);
Assert.Equal("bob", connection.Query<string>("set @age = 11 select @name", p).First());
Assert.Equal(11, p.Get<int>("age"));
}
[Fact]
......@@ -817,11 +878,11 @@ public void TestSupportForDynamicParametersOutputExpressions()
SET @AddressName = 'bobs burgers'
SET @AddressPersonId = @PersonId", p);
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
}
[Fact]
......@@ -846,12 +907,12 @@ public void TestSupportForDynamicParametersOutputExpressions_Scalar()
SET @AddressPersonId = @PersonId
select 42", p);
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
}
......@@ -877,12 +938,12 @@ public void TestSupportForDynamicParametersOutputExpressions_Query_Buffered()
SET @AddressPersonId = @PersonId
select 42", p, buffered: true).Single();
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
}
......@@ -908,12 +969,12 @@ public void TestSupportForDynamicParametersOutputExpressions_Query_NonBuffered()
SET @AddressPersonId = @PersonId
select 42", p, buffered: false).Single();
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
result.IsEqualTo(42);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, result);
}
}
......@@ -945,13 +1006,13 @@ select 17
y = multi.Read<int>().Single();
}
bob.Occupation.IsEqualTo("grillmaster");
bob.PersonId.IsEqualTo(2);
bob.NumberOfLegs.IsEqualTo(1);
bob.Address.Name.IsEqualTo("bobs burgers");
bob.Address.PersonId.IsEqualTo(2);
x.IsEqualTo(42);
y.IsEqualTo(17);
Assert.Equal("grillmaster", bob.Occupation);
Assert.Equal(2, bob.PersonId);
Assert.Equal(1, bob.NumberOfLegs);
Assert.Equal("bobs burgers", bob.Address.Name);
Assert.Equal(2, bob.Address.PersonId);
Assert.Equal(42, x);
Assert.Equal(17, y);
}
}
......@@ -962,7 +1023,7 @@ public void TestSupportForExpandoObjectParameters()
p.name = "bob";
object parameters = p;
string result = connection.Query<string>("select @name", parameters).First();
result.IsEqualTo("bob");
Assert.Equal("bob", result);
}
[Fact]
......@@ -978,7 +1039,7 @@ public void SO25069578_DynamicParams_Procs()
var row = connection.Query<HazX>("SO25069578", parameters,
commandType: CommandType.StoredProcedure, transaction: tran).Single();
tran.Rollback();
row.X.IsEqualTo("bar");
Assert.Equal("bar", row.X);
}
public class HazX
......@@ -1005,9 +1066,9 @@ public void SO25297173_DynamicIn()
var dynamicParams = new DynamicParameters(queryParams);
List<int> result = connection.Query<int>(query, dynamicParams).ToList();
result.Count.IsEqualTo(2);
result.Contains(5).IsTrue();
result.Contains(6).IsTrue();
Assert.Equal(2, result.Count);
Assert.Contains(5, result);
Assert.Contains(6, result);
}
[Fact]
......@@ -1017,7 +1078,19 @@ public void Test_AddDynamicParametersRepeatedShouldWork()
args.AddDynamicParams(new { Foo = 123 });
args.AddDynamicParams(new { Foo = 123 });
int i = connection.Query<int>("select @Foo", args).Single();
i.IsEqualTo(123);
Assert.Equal(123, i);
}
[Fact]
public void Test_AddDynamicParametersRepeatedIfParamTypeIsDbStiringShouldWork()
{
var foo = new DbString() { Value = "123" };
var args = new DynamicParameters();
args.AddDynamicParams(new { Foo = foo });
args.AddDynamicParams(new { Foo = foo });
int i = connection.Query<int>("select @Foo", args).Single();
Assert.Equal(123, i);
}
[Fact]
......@@ -1058,8 +1131,8 @@ public void TestMultipleParametersWithIndexer()
{
var order = connection.Query<MultipleParametersWithIndexer>("select 1 A,2 B").First();
order.A.IsEqualTo(1);
order.B.IsEqualTo(2);
Assert.Equal(1, order.A);
Assert.Equal(2, order.B);
}
public class MultipleParametersWithIndexer : MultipleParametersWithIndexerDeclaringType
......@@ -1094,9 +1167,9 @@ public void Issue182_BindDynamicObjectParametersAndColumns()
var result = connection.Execute("insert into #Dyno ([Id], [Name], [Foo]) values (@Id, @Name, @Foo);", orig);
var fromDb = connection.Query<Dyno>("select * from #Dyno where Id=@Id", orig).Single();
((Guid)fromDb.Id).IsEqualTo(guid);
fromDb.Name.IsEqualTo("T Rex");
((long)fromDb.Foo).IsEqualTo(123L);
Assert.Equal((Guid)fromDb.Id, guid);
Assert.Equal("T Rex", fromDb.Name);
Assert.Equal(123L, (long)fromDb.Foo);
}
public class Dyno
......@@ -1126,7 +1199,7 @@ public void Issue151_ExpandoObjectArgsExec()
args.Id = 123;
args.Name = "abc";
connection.Execute("create table #issue151 (Id int not null, Name nvarchar(20) not null)");
connection.Execute("insert #issue151 values(@Id, @Name)", (object)args).IsEqualTo(1);
Assert.Equal(1, connection.Execute("insert #issue151 values(@Id, @Name)", (object)args));
var row = connection.Query("select Id, Name from #issue151").Single();
((int)row.Id).Equals(123);
((string)row.Name).Equals("abc");
......@@ -1142,8 +1215,8 @@ public void Issue192_InParameterWorksWithSimilarNames()
insert @Issue192(Field_1) values (1), (2), (3);
SELECT * FROM @Issue192 WHERE Field IN @Field AND Field_1 IN @Field_1",
new { Field = new[] { 1, 2 }, Field_1 = new[] { 2, 3 } }).Single();
((int)rows.Field).IsEqualTo(2);
((int)rows.Field_1).IsEqualTo(2);
Assert.Equal(2, (int)rows.Field);
Assert.Equal(2, (int)rows.Field_1);
}
[Fact]
......@@ -1156,16 +1229,18 @@ public void Issue192_InParameterWorksWithSimilarNamesWithUnicode()
insert @Issue192(Field_1) values (1), (2), (3);
SELECT * FROM @Issue192 WHERE Field IN @µ AND Field_1 IN @µµ",
new { µ = new[] { 1, 2 }, µµ = new[] { 2, 3 } }).Single();
((int)rows.Field).IsEqualTo(2);
((int)rows.Field_1).IsEqualTo(2);
Assert.Equal(2, (int)rows.Field);
Assert.Equal(2, (int)rows.Field_1);
}
[FactUnlessCaseSensitiveDatabase]
public void Issue220_InParameterCanBeSpecifiedInAnyCase()
{
// note this might fail if your database server is case-sensitive
Assert.Equal(
new[] { 1 },
connection.Query<int>("select * from (select 1 as Id) as X where Id in @ids", new { Ids = new[] { 1 } })
.IsSequenceEqualTo(new[] { 1 });
);
}
[Fact]
......@@ -1174,7 +1249,7 @@ public void SO30156367_DynamicParamsWithoutExec()
var dbParams = new DynamicParameters();
dbParams.Add("Field1", 1);
var value = dbParams.Get<int>("Field1");
value.IsEqualTo(1);
Assert.Equal(1, value);
}
[Fact]
......@@ -1199,7 +1274,7 @@ private void RunAllStringSplitTests(int stringSplit, int max = 150)
int count = connection.QuerySingle<int>("create table #splits (i int not null);"
+ string.Concat(Enumerable.Range(-max, max * 3).Select(i => $"insert #splits (i) values ({i});"))
+ "select count(1) from #splits");
count.IsEqualTo(3 * max);
Assert.Equal(count, 3 * max);
for (int i = 0; i < max; Incr(ref i))
{
......@@ -1207,8 +1282,8 @@ private void RunAllStringSplitTests(int stringSplit, int max = 150)
{
var vals = Enumerable.Range(1, i);
var list = connection.Query<int>("select i from #splits where i in @vals", new { vals }).AsList();
list.Count.IsEqualTo(i);
list.Sum().IsEqualTo(vals.Sum());
Assert.Equal(list.Count, i);
Assert.Equal(list.Sum(), vals.Sum());
}
catch (Exception ex)
{
......@@ -1236,7 +1311,7 @@ public void Issue601_InternationalParameterNamesWork()
{
// regular parameter
var result = connection.QuerySingle<int>("select @æøå٦", new { æøå٦ = 42 });
result.IsEqualTo(42);
Assert.Equal(42, result);
}
[Fact]
......@@ -1251,7 +1326,7 @@ private void TestListExpansionPadding(bool enabled)
try
{
SqlMapper.Settings.PadListExpansions = enabled;
connection.ExecuteScalar<int>(@"
Assert.Equal(4096, connection.ExecuteScalar<int>(@"
create table #ListExpansion(id int not null identity(1,1), value int null);
insert #ListExpansion (value) values (null);
declare @loop int = 0;
......@@ -1261,7 +1336,7 @@ private void TestListExpansionPadding(bool enabled)
set @loop = @loop + 1;
end
select count(1) as [Count] from #ListExpansion").IsEqualTo(4096);
select count(1) as [Count] from #ListExpansion"));
var list = new List<int>();
int nextId = 1, batchCount;
......@@ -1307,9 +1382,9 @@ private void TestListForExpansion(List<int> list, bool enabled)
string query = row.Query;
int argCount = Regex.Matches(query, "@ids[0-9]").Count;
int expectedCount = GetExpectedListExpansionCount(list.Count, enabled);
hits.IsEqualTo(list.Count);
misses.IsEqualTo(list.Count);
argCount.IsEqualTo(expectedCount);
Assert.Equal(hits, list.Count);
Assert.Equal(misses, list.Count);
Assert.Equal(argCount, expectedCount);
}
private static int GetExpectedListExpansionCount(int count, bool enabled)
......
......@@ -26,7 +26,7 @@ @Bar int
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);
Assert.Equal(7, args.Get<int>("ID"));
}
[Fact]
......@@ -50,8 +50,8 @@ @Bar int
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);
Assert.Equal(7, args.Get<int>("ID"));
Assert.Equal(42, args.Get<int>("result"));
}
[Fact]
......@@ -78,12 +78,12 @@ public void TestIssue17648290()
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);
Assert.Equal(2, (int)row.MessageProcessID);
Assert.Equal(38349348, (int)row.StartNum);
Assert.Equal(3874900, (int)row.EndNum);
DateTime startDate = row.StartDate, endDate = row.EndDate;
p.Get<int>("SuccessCode").IsEqualTo(0);
p.Get<string>("ErrorDescription").IsEqualTo("Completed successfully");
Assert.Equal(0, p.Get<int>("SuccessCode"));
Assert.Equal("Completed successfully", p.Get<string>("ErrorDescription"));
}
[Fact]
......@@ -97,13 +97,13 @@ public void SO24605346_ProcsAndStrings()
TaxInvoiceNumber = InvoiceNumber
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
result.TaxInvoiceNumber.IsEqualTo("INV0000000028PPN");
Assert.Equal("INV0000000028PPN", result.TaxInvoiceNumber);
}
private class PracticeRebateOrders
{
public string fTaxInvoiceNumber;
#if !COREFX
#if !NETCOREAPP1_0
[System.Xml.Serialization.XmlElement(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
#endif
public string TaxInvoiceNumber
......@@ -125,8 +125,8 @@ public void Issue327_ReadEmptyProcedureResults()
var query = connection.QueryMultiple("#TestEmptyResults", commandType: CommandType.StoredProcedure);
var result1 = query.Read<Issue327_Person>();
var result2 = query.Read<Issue327_Magic>();
result1.Any().IsFalse();
result2.Any().IsFalse();
Assert.False(result1.Any());
Assert.False(result2.Any());
}
private class Issue327_Person
......@@ -159,10 +159,10 @@ public void TestProcSupport()
select 1111
return @a
end");
connection.Query<int>("#TestProc", p, commandType: CommandType.StoredProcedure).First().IsEqualTo(1111);
Assert.Equal(1111, connection.Query<int>("#TestProc", p, commandType: CommandType.StoredProcedure).First());
p.Get<int>("c").IsEqualTo(11);
p.Get<int>("b").IsEqualTo(999);
Assert.Equal(11, p.Get<int>("c"));
Assert.Equal(999, p.Get<int>("b"));
}
// https://stackoverflow.com/q/8593871
......@@ -178,10 +178,10 @@ public void TestListOfAnsiStrings()
}
}).ToList();
results.Count.IsEqualTo(2);
Assert.Equal(2, results.Count);
results.Sort();
results[0].IsEqualTo("a");
results[1].IsEqualTo("b");
Assert.Equal("a", results[0]);
Assert.Equal("b", results[1]);
}
}
}
......@@ -4,6 +4,7 @@
namespace Dapper.Tests.Providers
{
[Collection("TypeHandlerTests")]
public class EntityFrameworkTests : TestBase
{
public EntityFrameworkTests()
......@@ -23,8 +24,8 @@ public void Issue570_DbGeo_HasValues()
var fromDb = connection.QuerySingle<DbGeography>("declare @geos table(geo geography); insert @geos(geo) values(@val); select * from @geos",
new { val = orig });
fromDb.Area.IsNotNull();
fromDb.Area.IsEqualTo(orig.Area);
Assert.NotNull(fromDb.Area);
Assert.Equal(orig.Area, fromDb.Area);
}
#endif
......@@ -33,7 +34,7 @@ public void Issue22_ExecuteScalar_EntityFramework()
{
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();
Assert.NotNull(geo2);
}
}
}
......
#if FIREBIRD
using FirebirdSql.Data.FirebirdClient;
using FirebirdSql.Data.FirebirdClient;
using System.Data;
using System.Linq;
using Xunit;
......@@ -11,12 +10,12 @@ public class FirebirdTests : TestBase
[Fact(Skip = "Bug in Firebird; a PR to fix it has been submitted")]
public void Issue178_Firebird()
{
const string cs = @"initial catalog=localhost:database;user id=SYSDBA;password=masterkey";
const string 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";
const string sql = "select count(*) from Issue178";
try { connection.Execute("drop table Issue178"); }
catch { /* don't care */ }
connection.Execute("create table Issue178(id int not null)");
......@@ -25,25 +24,24 @@ public void Issue178_Firebird()
using (var sqlCmd = new FbCommand(sql, connection))
using (IDataReader reader1 = sqlCmd.ExecuteReader())
{
Assert.IsTrue(reader1.Read());
reader1.GetInt32(0).IsEqualTo(1);
Assert.IsFalse(reader1.Read());
Assert.IsFalse(reader1.NextResult());
Assert.True(reader1.Read());
Assert.Equal(1, reader1.GetInt32(0));
Assert.False(reader1.Read());
Assert.False(reader1.NextResult());
}
// dapper
using (var reader2 = connection.ExecuteReader(sql))
{
Assert.IsTrue(reader2.Read());
reader2.GetInt32(0).IsEqualTo(1);
Assert.IsFalse(reader2.Read());
Assert.IsFalse(reader2.NextResult());
Assert.True(reader2.Read());
Assert.Equal(1, reader2.GetInt32(0));
Assert.False(reader2.Read());
Assert.False(reader2.NextResult());
}
var count = connection.Query<int>(sql).Single();
count.IsEqualTo(1);
Assert.Equal(1, count);
}
}
}
}
\ No newline at end of file
#endif
\ No newline at end of file
......@@ -19,7 +19,7 @@ public void TestLinqBinaryToClass()
var output = connection.Query<WithBinary>("select @input as [Value]", new { input }).First().Value;
output.ToArray().IsSequenceEqualTo(orig);
Assert.Equal(orig, output.ToArray());
}
[Fact]
......@@ -31,13 +31,33 @@ public void TestLinqBinaryRaw()
var output = connection.Query<System.Data.Linq.Binary>("select @input as [Value]", new { input }).First();
output.ToArray().IsSequenceEqualTo(orig);
Assert.Equal(orig, output.ToArray());
}
private class WithBinary
{
public System.Data.Linq.Binary Value { get; set; }
}
private class NoDefaultConstructorWithBinary
{
public System.Data.Linq.Binary Value { get; set; }
public int Ynt { get; set; }
public NoDefaultConstructorWithBinary(System.Data.Linq.Binary val)
{
Value = val;
}
}
[Fact]
public void TestNoDefaultConstructorBinary()
{
byte[] orig = new byte[20];
new Random(123456).NextBytes(orig);
var input = new System.Data.Linq.Binary(orig);
var output = connection.Query<NoDefaultConstructorWithBinary>("select @input as val", new { input }).First().Value;
Assert.Equal(orig, output.ToArray());
}
}
}
#endif
\ No newline at end of file
#if MYSQL
using System;
using System;
using System.Linq;
using Xunit;
......@@ -55,14 +54,14 @@ public void Issue552_SignedUnsignedBooleans()
var rows = conn.Query<MySqlHasBool>("select * from bar;").ToDictionary(x => x.Id);
rows[1].Bool_Val.IsNull();
rows[2].Bool_Val.IsEqualTo(false);
rows[3].Bool_Val.IsEqualTo(true);
rows[4].Bool_Val.IsNull();
rows[5].Bool_Val.IsEqualTo(true);
rows[6].Bool_Val.IsEqualTo(false);
rows[7].Bool_Val.IsNull();
rows[8].Bool_Val.IsEqualTo(true);
Assert.Null(rows[1].Bool_Val);
Assert.False(rows[2].Bool_Val);
Assert.True(rows[3].Bool_Val);
Assert.Null(rows[4].Bool_Val);
Assert.True(rows[5].Bool_Val);
Assert.False(rows[6].Bool_Val);
Assert.Null(rows[7].Bool_Val);
Assert.True(rows[8].Bool_Val);
}
}
......@@ -126,8 +125,8 @@ public void Issue426_SO34439033_DateTimeGainsTicks()
conn.Execute("replace into Issue426_Test values (@Id,@Time)", localObj);
var dbObj = conn.Query<Issue426_Test>("select * from Issue426_Test where Id = @id", new { id = Id }).Single();
dbObj.Id.IsEqualTo(Id);
dbObj.Time.Value.Ticks.IsEqualTo(ticks);
Assert.Equal(Id, dbObj.Id);
Assert.Equal(ticks, dbObj.Time.Value.Ticks);
}
}
......@@ -143,10 +142,10 @@ public void SO36303462_Tinyint_Bools()
conn.Execute("insert SO36303462_Test (Id, IsBold) values (3,1);");
var rows = conn.Query<SO36303462>("select * from SO36303462_Test").ToDictionary(x => x.Id);
rows.Count.IsEqualTo(3);
rows[1].IsBold.IsTrue();
rows[2].IsBold.IsFalse();
rows[3].IsBold.IsTrue();
Assert.Equal(3, rows.Count);
Assert.True(rows[1].IsBold);
Assert.False(rows[2].IsBold);
Assert.True(rows[3].IsBold);
}
}
......@@ -162,6 +161,7 @@ public class Issue426_Test
public TimeSpan? Time { get; set; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class FactMySqlAttribute : FactAttribute
{
public override string Skip
......@@ -186,4 +186,3 @@ static FactMySqlAttribute()
}
}
}
#endif
......@@ -31,8 +31,8 @@ public void TestOleDbParameters()
).Single();
int age = row.Age;
int id = row.Id;
age.IsEqualTo(23);
id.IsEqualTo(12);
Assert.Equal(23, age);
Assert.Equal(12, id);
}
}
......@@ -42,7 +42,7 @@ public void PseudoPositionalParameters_Simple()
using (var connection = GetOleDbConnection())
{
int value = connection.Query<int>("select ?x? + ?y_2? + ?z?", new { x = 1, y_2 = 3, z = 5, z2 = 24 }).Single();
value.IsEqualTo(9);
Assert.Equal(9, value);
}
}
......@@ -67,7 +67,7 @@ public void PseudoPositionalParameters_Dynamic()
args.Add("z", 5);
args.Add("z2", 24);
int value = connection.Query<int>("select ?x? + ?y_2? + ?z?", args).Single();
value.IsEqualTo(9);
Assert.Equal(9, value);
}
}
......@@ -76,15 +76,8 @@ public void PseudoPositionalParameters_ReusedParameter()
{
using (var connection = GetOleDbConnection())
{
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");
}
var ex = Assert.Throws<InvalidOperationException>(() => connection.Query<int>("select ?x? + ?y_2? + ?x?", new { x = 1, y_2 = 3 }).Single());
Assert.Equal("When passing parameters by position, each parameter can only be referenced once", ex.Message);
}
}
......@@ -96,7 +89,7 @@ public void Issue569_SO38527197_PseudoPositionalParameters_In()
int[] ids = { 1, 2, 5, 7 };
var list = connection.Query<int>("select * from string_split('1,2,3,4,5',',') where value in ?ids?", new { ids }).AsList();
list.Sort();
string.Join(",", list).IsEqualTo("1,2,5");
Assert.Equal("1,2,5", string.Join(",", list));
}
}
......@@ -109,8 +102,8 @@ public void PseudoPositional_CanUseVariable()
var row = connection.QuerySingle("declare @id int = ?id?; select @id as [A], @id as [B];", new { id });
int a = (int)row.A;
int b = (int)row.B;
a.IsEqualTo(42);
b.IsEqualTo(42);
Assert.Equal(42, a);
Assert.Equal(42, b);
}
}
......@@ -119,16 +112,12 @@ public void PseudoPositional_CannotUseParameterMultipleTimes()
{
using (var connection = GetOleDbConnection())
{
try
var ex = Assert.Throws<InvalidOperationException>(() =>
{
const int id = 42;
var row = connection.QuerySingle("select ?id? as [A], ?id? as [B];", new { id });
Assert.Fail();
}
catch (InvalidOperationException ex) when (ex.Message == "When passing parameters by position, each parameter can only be referenced once")
{
// that's a win
}
connection.QuerySingle("select ?id? as [A], ?id? as [B];", new { id });
});
Assert.Equal("When passing parameters by position, each parameter can only be referenced once", ex.Message);
}
}
......@@ -141,8 +130,8 @@ public void PseudoPositionalParameters_ExecSingle()
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);
Assert.Equal(1, count);
Assert.Equal(6, sum);
}
}
......@@ -160,8 +149,8 @@ public void PseudoPositionalParameters_ExecMulti()
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);
Assert.Equal(3, count);
Assert.Equal(10, sum);
}
}
......@@ -187,8 +176,8 @@ public void Issue457_NullParameterValues()
var a = (DateTime?)row.Since;
var b = (string)row.Code;
a.IsEqualTo(since);
b.IsEqualTo(code);
Assert.Equal(since, a);
Assert.Equal(code, b);
}
}
......@@ -214,8 +203,8 @@ public void Issue457_NullParameterValues_Named()
var a = (DateTime?)row.Since;
var b = (string)row.Code;
a.IsEqualTo(since);
b.IsEqualTo(code);
Assert.Equal(since, a);
Assert.Equal(code, b);
}
}
......@@ -243,8 +232,8 @@ public async void Issue457_NullParameterValues_MultiAsync()
var a = (DateTime?)row.Since;
var b = (string)row.Code;
a.IsEqualTo(since);
b.IsEqualTo(code);
Assert.Equal(a, since);
Assert.Equal(b, code);
}
}
}
......@@ -273,8 +262,8 @@ public async void Issue457_NullParameterValues_MultiAsync_Named()
var a = (DateTime?)row.Since;
var b = (string)row.Code;
a.IsEqualTo(since);
b.IsEqualTo(code);
Assert.Equal(a, since);
Assert.Equal(b, code);
}
}
}
......
#if POSTGRESQL
using System;
using System;
using System.Data;
using System.Linq;
using Xunit;
......@@ -49,14 +48,15 @@ public void TestPostgresqlArrayParameters()
conn.Execute("insert into tcat(breed, name) values(:breed, :name) ", Cats);
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);
Assert.Equal(3, r.Count());
Assert.Equal(1, r.Count(c => c.Id == 1));
Assert.Equal(1, r.Count(c => c.Id == 3));
Assert.Equal(1, r.Count(c => c.Id == 5));
transaction.Rollback();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class FactPostgresqlAttribute : FactAttribute
{
public override string Skip
......@@ -81,4 +81,3 @@ static FactPostgresqlAttribute()
}
}
}
\ No newline at end of file
#endif
\ No newline at end of file
......@@ -29,11 +29,11 @@ public void MultiRSSqlCE()
cnn.Execute("insert Posts values(2,'title2','body2',null)");
cnn.Execute("insert Authors values(1,'sam')");
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();
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();
var firstPost = data[0];
firstPost.Title.IsEqualTo("title");
firstPost.Author.Name.IsEqualTo("sam");
data[1].Author.IsNull();
Assert.Equal("title", firstPost.Title);
Assert.Equal("sam", firstPost.Author.Name);
Assert.Null(data[1].Author);
}
}
......
#if SQLITE
using Microsoft.Data.Sqlite;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;
using Xunit;
namespace Dapper.Tests
{
public class SqliteTests : TestBase
{
protected static SQLiteConnection GetSQLiteConnection(bool open = true)
protected static SqliteConnection GetSQLiteConnection(bool open = true)
{
var connection = new SQLiteConnection("Data Source=:memory:");
var connection = new SqliteConnection("Data Source=:memory:");
if (open) connection.Open();
return connection;
}
......@@ -26,6 +24,9 @@ public void DapperEnumValue_Sqlite()
}
}
[Collection(NonParallelDefinition.Name)]
public class SqliteTypeHandlerTests : TestBase
{
[FactSqlite]
public void Issue466_SqliteHatesOptimizations()
{
......@@ -33,15 +34,15 @@ public void Issue466_SqliteHatesOptimizations()
{
SqlMapper.ResetTypeHandlers();
var row = connection.Query<HazNameId>("select 42 as Id").First();
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
row = connection.Query<HazNameId>("select 42 as Id").First();
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
SqlMapper.ResetTypeHandlers();
row = connection.QueryFirst<HazNameId>("select 42 as Id");
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
row = connection.QueryFirst<HazNameId>("select 42 as Id");
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
}
}
......@@ -52,15 +53,16 @@ public async Task Issue466_SqliteHatesOptimizations_Async()
{
SqlMapper.ResetTypeHandlers();
var row = (await connection.QueryAsync<HazNameId>("select 42 as Id").ConfigureAwait(false)).First();
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
row = (await connection.QueryAsync<HazNameId>("select 42 as Id").ConfigureAwait(false)).First();
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
SqlMapper.ResetTypeHandlers();
row = await connection.QueryFirstAsync<HazNameId>("select 42 as Id").ConfigureAwait(false);
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
row = await connection.QueryFirstAsync<HazNameId>("select 42 as Id").ConfigureAwait(false);
row.Id.IsEqualTo(42);
Assert.Equal(42, row.Id);
}
}
}
......@@ -82,17 +84,14 @@ private void Isse467_SqliteParameterNaming(bool prefix)
{
var cmd = connection.CreateCommand();
cmd.CommandText = "select @foo";
#if NET45
const DbType type = DbType.Int32;
#else
const SqliteType type = SqliteType.Integer;
#endif
cmd.Parameters.Add(prefix ? "@foo" : "foo", type).Value = 42;
var i = Convert.ToInt32(cmd.ExecuteScalar());
i.IsEqualTo(42);
Assert.Equal(42, i);
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class FactSqliteAttribute : FactAttribute
{
public override string Skip
......@@ -119,4 +118,3 @@ static FactSqliteAttribute()
}
}
}
\ No newline at end of file
#endif
\ No newline at end of file
......@@ -63,7 +63,7 @@ public void TestQueryMultipleNonBufferedCorrectOrder()
[Fact]
public void TestMultiReaderBasic()
{
const string sql = @"select 1 as Id union all select 2 as Id select 'abc' as name select 1 as Id union all select 2 as Id";
const string sql = "select 1 as Id union all select 2 as Id select 'abc' as name select 1 as Id union all select 2 as Id";
int i, j;
string s;
using (var multi = connection.QueryMultiple(sql))
......@@ -72,9 +72,9 @@ public void TestMultiReaderBasic()
s = multi.Read<string>().Single();
j = multi.Read<int>().Sum();
}
Assert.IsEqualTo(i, 1);
Assert.IsEqualTo(s, "abc");
Assert.IsEqualTo(j, 3);
Assert.Equal(1, i);
Assert.Equal("abc", s);
Assert.Equal(3, j);
}
[Fact]
......@@ -102,11 +102,11 @@ public void TestReadDynamicWithGridReader()
var users = grid.Read().ToList();
var posts = grid.Read().ToList();
users.Count.IsEqualTo(2);
posts.Count.IsEqualTo(3);
Assert.Equal(2, users.Count);
Assert.Equal(3, posts.Count);
((int)users[0].Id).IsEqualTo(2);
((int)posts[0].Id).IsEqualTo(3);
Assert.Equal(2, (int)users[0].Id);
Assert.Equal(3, (int)posts[0].Id);
}
finally
{
......@@ -133,7 +133,7 @@ select @b
reader.Read();
}
var retVal = p.Get<int>("RetVal");
retVal.IsEqualTo(3);
Assert.Equal(3, retVal);
}
[Fact]
......@@ -141,14 +141,14 @@ public void Issue524_QueryMultiple_Cast()
{
// aka: Read<int> should work even if the data is a <long>
// using regular API
connection.Query<int>("select cast(42 as bigint)").Single().IsEqualTo(42);
connection.QuerySingle<int>("select cast(42 as bigint)").IsEqualTo(42);
Assert.Equal(42, connection.Query<int>("select cast(42 as bigint)").Single());
Assert.Equal(42, connection.QuerySingle<int>("select cast(42 as bigint)"));
// using multi-reader API
using(var reader = connection.QueryMultiple("select cast(42 as bigint); select cast(42 as bigint)"))
{
reader.Read<int>().Single().IsEqualTo(42);
reader.ReadSingle<int>().IsEqualTo(42);
Assert.Equal(42, reader.Read<int>().Single());
Assert.Equal(42, reader.ReadSingle<int>());
}
}
......@@ -159,10 +159,10 @@ public void QueryMultipleFromClosed()
{
using (var multi = conn.QueryMultiple("select 1; select 'abc';"))
{
multi.Read<int>().Single().IsEqualTo(1);
multi.Read<string>().Single().IsEqualTo("abc");
Assert.Equal(1, multi.Read<int>().Single());
Assert.Equal("abc", multi.Read<string>().Single());
}
conn.State.IsEqualTo(ConnectionState.Closed);
Assert.Equal(ConnectionState.Closed, conn.State);
}
}
......@@ -171,14 +171,14 @@ public void QueryMultiple2FromClosed()
{
using (var conn = GetClosedConnection())
{
conn.State.IsEqualTo(ConnectionState.Closed);
Assert.Equal(ConnectionState.Closed, conn.State);
using (var multi = conn.QueryMultiple("select 1 select 2 select 3"))
{
multi.Read<int>().Single().IsEqualTo(1);
multi.Read<int>().Single().IsEqualTo(2);
Assert.Equal(1, multi.Read<int>().Single());
Assert.Equal(2, multi.Read<int>().Single());
// not reading 3 is intentional here
}
conn.State.IsEqualTo(ConnectionState.Closed);
Assert.Equal(ConnectionState.Closed, conn.State);
}
}
......@@ -192,10 +192,10 @@ public void SO35554284_QueryMultipleUntilConsumed()
{
items.AddRange(reader.Read<HazNameId>());
}
items.Count.IsEqualTo(3);
items[0].Id.IsEqualTo(1);
items[1].Id.IsEqualTo(2);
items[2].Id.IsEqualTo(3);
Assert.Equal(3, items.Count);
Assert.Equal(1, items[0].Id);
Assert.Equal(2, items[1].Id);
Assert.Equal(3, items[2].Id);
}
}
......@@ -204,15 +204,8 @@ 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);
}
Assert.ThrowsAny<Exception>(() => conn.QueryMultiple("select gibberish"));
Assert.Equal(ConnectionState.Closed, conn.State);
}
}
......@@ -237,15 +230,15 @@ private void TestMultiSelectWithSomeEmptyGrids(bool buffered)
}
catch (ObjectDisposedException ex)
{ // expected; success
ex.Message.IsEqualTo("The reader has been disposed; this can happen after all data has been consumed\r\nObject name: 'Dapper.SqlMapper+GridReader'.");
Assert.Equal("The reader has been disposed; this can happen after all data has been consumed\r\nObject name: 'Dapper.SqlMapper+GridReader'.", ex.Message);
}
one.Length.IsEqualTo(1);
one[0].IsEqualTo(1);
two.Length.IsEqualTo(0);
three.Length.IsEqualTo(0);
four.Length.IsEqualTo(1);
four[0].IsEqualTo(4);
Assert.Single(one);
Assert.Equal(1, one[0]);
Assert.Empty(two);
Assert.Empty(three);
Assert.Single(four);
Assert.Equal(4, four[0]);
}
}
......@@ -261,17 +254,17 @@ public void TypeBasedViaTypeMulti()
first = multi.Read(type).Single();
second = multi.Read(type).Single();
}
((object)first).GetType().IsEqualTo(type);
Assert.Equal(((object)first).GetType(), type);
int a = first.A;
string b = first.B;
a.IsEqualTo(123);
b.IsEqualTo("abc");
Assert.Equal(123, a);
Assert.Equal("abc", b);
((object)second).GetType().IsEqualTo(type);
Assert.Equal(((object)second).GetType(), type);
a = second.A;
b = second.B;
a.IsEqualTo(456);
b.IsEqualTo("def");
Assert.Equal(456, a);
Assert.Equal("def", b);
}
}
}
......@@ -2,7 +2,8 @@
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
#if !COREFX
using Xunit;
#if !NETCOREAPP1_0
using System.Threading;
#endif
......@@ -45,7 +46,7 @@ public SqlConnection GetClosedConnection()
protected static CultureInfo ActiveCulture
{
#if COREFX
#if NETCOREAPP1_0
get { return CultureInfo.CurrentCulture; }
set { CultureInfo.CurrentCulture = value; }
#else
......@@ -58,8 +59,8 @@ static TestBase()
{
Console.WriteLine("Dapper: " + typeof(SqlMapper).AssemblyQualifiedName);
Console.WriteLine("Using Connectionstring: {0}", ConnectionString);
#if COREFX
Console.WriteLine("CoreCLR");
#if NETCOREAPP1_0
Console.WriteLine("CoreCLR (netcoreapp1.0)");
#else
Console.WriteLine(".NET: " + Environment.Version);
Console.Write("Loading native assemblies for SQL types...");
......@@ -81,4 +82,10 @@ public void Dispose()
_connection?.Dispose();
}
}
[CollectionDefinition(Name, DisableParallelization = true)]
public class NonParallelDefinition : TestBase
{
public const string Name = "NonParallel";
}
}
......@@ -23,7 +23,7 @@ public void TestTransactionCommit()
transaction.Commit();
}
connection.Query<int>("select count(*) from #TransactionTest;").Single().IsEqualTo(1);
Assert.Equal(1, connection.Query<int>("select count(*) from #TransactionTest;").Single());
}
finally
{
......@@ -45,7 +45,7 @@ public void TestTransactionRollback()
transaction.Rollback();
}
connection.Query<int>("select count(*) from #TransactionTest;").Single().IsEqualTo(0);
Assert.Equal(0, connection.Query<int>("select count(*) from #TransactionTest;").Single());
}
finally
{
......@@ -69,7 +69,7 @@ public void TestCommandWithInheritedTransaction()
transaction.Rollback();
}
connection.Query<int>("select count(*) from #TransactionTest;").Single().IsEqualTo(0);
Assert.Equal(0, connection.Query<int>("select count(*) from #TransactionTest;").Single());
}
finally
{
......
......@@ -8,38 +8,30 @@ public class TupleTests : TestBase
[Fact]
public void TupleStructParameter_Fails_HelpfulMessage()
{
try
{
// I can see this happening...
connection.QuerySingle<int>("select @id", (id: 42, name: "Fred"));
Assert.Fail();
}
catch (NotSupportedException ex)
{
ex.Message.IsEqualTo("ValueTuple should not be used for parameters - the language-level names are not available to use as parameter names, and it adds unnecessary boxing");
}
var ex = Assert.Throws<NotSupportedException>(() => connection.QuerySingle<int>("select @id", (id: 42, name: "Fred")));
Assert.Equal("ValueTuple should not be used for parameters - the language-level names are not available to use as parameter names, and it adds unnecessary boxing", ex.Message);
}
[Fact]
public void TupleClassParameter_Works()
{
connection.QuerySingle<int>("select @Item1", Tuple.Create(42, "Fred")).IsEqualTo(42);
Assert.Equal(42, connection.QuerySingle<int>("select @Item1", Tuple.Create(42, "Fred")));
}
[Fact]
public void TupleReturnValue_Works_ByPosition()
{
var val = connection.QuerySingle<(int id, string name)>("select 42, 'Fred'");
val.id.IsEqualTo(42);
val.name.IsEqualTo("Fred");
Assert.Equal(42, val.id);
Assert.Equal("Fred", val.name);
}
[Fact]
public void TupleReturnValue_TooManyColumns_Ignored()
{
var val = connection.QuerySingle<(int id, string name)>("select 42, 'Fred', 123");
val.id.IsEqualTo(42);
val.name.IsEqualTo("Fred");
Assert.Equal(42, val.id);
Assert.Equal("Fred", val.name);
}
[Fact]
......@@ -47,17 +39,17 @@ public void TupleReturnValue_TooFewColumns_Unmapped()
{
// I'm very wary of making this throw, but I can also see some sense in pointing out the oddness
var val = connection.QuerySingle<(int id, string name, int extra)>("select 42, 'Fred'");
val.id.IsEqualTo(42);
val.name.IsEqualTo("Fred");
val.extra.IsEqualTo(0);
Assert.Equal(42, val.id);
Assert.Equal("Fred", val.name);
Assert.Equal(0, val.extra);
}
[Fact]
public void TupleReturnValue_Works_NamesIgnored()
{
var val = connection.QuerySingle<(int id, string name)>("select 42 as [Item2], 'Fred' as [Item1]");
val.id.IsEqualTo(42);
val.name.IsEqualTo("Fred");
Assert.Equal(42, val.id);
Assert.Equal("Fred", val.name);
}
}
}
......@@ -8,6 +8,7 @@
namespace Dapper.Tests
{
[Collection(NonParallelDefinition.Name)]
public class TypeHandlerTests : TestBase
{
[Fact]
......@@ -17,13 +18,13 @@ public void TestChangingDefaultStringTypeMappingToAnsiString()
var param = new { testParam = "TestString" };
var result01 = connection.Query<string>(sql, param).FirstOrDefault();
result01.IsEqualTo("nvarchar");
Assert.Equal("nvarchar", result01);
SqlMapper.PurgeQueryCache();
SqlMapper.AddTypeMap(typeof(string), DbType.AnsiString); // Change Default String Handling to AnsiString
var result02 = connection.Query<string>(sql, param).FirstOrDefault();
result02.IsEqualTo("varchar");
Assert.Equal("varchar", result02);
SqlMapper.PurgeQueryCache();
SqlMapper.AddTypeMap(typeof(string), DbType.String); // Restore Default to Unicode String
......@@ -36,18 +37,63 @@ public void TestChangingDefaultStringTypeMappingToAnsiStringFirstOrDefault()
var param = new { testParam = "TestString" };
var result01 = connection.QueryFirstOrDefault<string>(sql, param);
result01.IsEqualTo("nvarchar");
Assert.Equal("nvarchar", result01);
SqlMapper.PurgeQueryCache();
SqlMapper.AddTypeMap(typeof(string), DbType.AnsiString); // Change Default String Handling to AnsiString
var result02 = connection.QueryFirstOrDefault<string>(sql, param);
result02.IsEqualTo("varchar");
Assert.Equal("varchar", result02);
SqlMapper.PurgeQueryCache();
SqlMapper.AddTypeMap(typeof(string), DbType.String); // Restore Default to Unicode String
}
[Fact]
public void TestCustomTypeMap()
{
// default mapping
var item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
Assert.Equal("AVal", item.A);
Assert.Equal("BVal", item.B);
// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping),
(type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);
item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
Assert.Equal("BVal", item.A);
Assert.Equal("AVal", item.B);
// reset to default
SqlMapper.SetTypeMap(typeof(TypeWithMapping), null);
item = connection.Query<TypeWithMapping>("Select 'AVal' as A, 'BVal' as B").Single();
Assert.Equal("AVal", item.A);
Assert.Equal("BVal", item.B);
}
private static string GetDescriptionFromAttribute(MemberInfo member)
{
if (member == null) return null;
#if NETCOREAPP1_0
var data = member.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(DescriptionAttribute));
return (string)data?.ConstructorArguments.Single().Value;
#else
var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
return attrib?.Description;
#endif
}
public class TypeWithMapping
{
[Description("B")]
public string A { get; set; }
[Description("A")]
public string B { get; set; }
}
[Fact]
public void Issue136_ValueTypeHandlers()
{
......@@ -176,134 +222,134 @@ private void TestBigIntForEverythingWorks_ByDataType<T>(string dbType)
{
using (var reader = connection.ExecuteReader("select cast(1 as " + dbType + ")"))
{
reader.Read().IsTrue();
Assert.True(reader.Read());
reader.GetFieldType(0).Equals(typeof(T));
reader.Read().IsFalse();
reader.NextResult().IsFalse();
Assert.False(reader.Read());
Assert.False(reader.NextResult());
}
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);
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);
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);
TestBigIntForEverythingWorks(LotsOfNumerics.E_UShort.B, dbType);
TestBigIntForEverythingWorks(LotsOfNumerics.E_Long.B, dbType);
TestBigIntForEverythingWorks(LotsOfNumerics.E_ULong.B, dbType);
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);
}
private void TestBigIntForEverythingWorks<T>(T expected, string dbType)
Assert.True(row.N_Bool);
Assert.Equal(row.N_SByte, (sbyte)1);
Assert.Equal(row.N_Byte, (byte)1);
Assert.Equal(row.N_Int, (int)1);
Assert.Equal(row.N_UInt, (uint)1);
Assert.Equal(row.N_Short, (short)1);
Assert.Equal(row.N_UShort, (ushort)1);
Assert.Equal(row.N_Long, (long)1);
Assert.Equal(row.N_ULong, (ulong)1);
Assert.Equal(row.N_Float, (float)1);
Assert.Equal(row.N_Double, (double)1);
Assert.Equal(row.N_Decimal, (decimal)1);
Assert.Equal(LotsOfNumerics.E_Byte.B, row.P_Byte);
Assert.Equal(LotsOfNumerics.E_SByte.B, row.P_SByte);
Assert.Equal(LotsOfNumerics.E_Short.B, row.P_Short);
Assert.Equal(LotsOfNumerics.E_UShort.B, row.P_UShort);
Assert.Equal(LotsOfNumerics.E_Int.B, row.P_Int);
Assert.Equal(LotsOfNumerics.E_UInt.B, row.P_UInt);
Assert.Equal(LotsOfNumerics.E_Long.B, row.P_Long);
Assert.Equal(LotsOfNumerics.E_ULong.B, row.P_ULong);
Assert.True(row.N_N_Bool.Value);
Assert.Equal(row.N_N_SByte.Value, (sbyte)1);
Assert.Equal(row.N_N_Byte.Value, (byte)1);
Assert.Equal(row.N_N_Int.Value, (int)1);
Assert.Equal(row.N_N_UInt.Value, (uint)1);
Assert.Equal(row.N_N_Short.Value, (short)1);
Assert.Equal(row.N_N_UShort.Value, (ushort)1);
Assert.Equal(row.N_N_Long.Value, (long)1);
Assert.Equal(row.N_N_ULong.Value, (ulong)1);
Assert.Equal(row.N_N_Float.Value, (float)1);
Assert.Equal(row.N_N_Double.Value, (double)1);
Assert.Equal(row.N_N_Decimal, (decimal)1);
Assert.Equal(LotsOfNumerics.E_Byte.B, row.N_P_Byte.Value);
Assert.Equal(LotsOfNumerics.E_SByte.B, row.N_P_SByte.Value);
Assert.Equal(LotsOfNumerics.E_Short.B, row.N_P_Short.Value);
Assert.Equal(LotsOfNumerics.E_UShort.B, row.N_P_UShort.Value);
Assert.Equal(LotsOfNumerics.E_Int.B, row.N_P_Int.Value);
Assert.Equal(LotsOfNumerics.E_UInt.B, row.N_P_UInt.Value);
Assert.Equal(LotsOfNumerics.E_Long.B, row.N_P_Long.Value);
Assert.Equal(LotsOfNumerics.E_ULong.B, row.N_P_ULong.Value);
TestBigIntForEverythingWorksGeneric<bool>(true, dbType);
TestBigIntForEverythingWorksGeneric<sbyte>((sbyte)1, dbType);
TestBigIntForEverythingWorksGeneric<byte>((byte)1, dbType);
TestBigIntForEverythingWorksGeneric<int>((int)1, dbType);
TestBigIntForEverythingWorksGeneric<uint>((uint)1, dbType);
TestBigIntForEverythingWorksGeneric<short>((short)1, dbType);
TestBigIntForEverythingWorksGeneric<ushort>((ushort)1, dbType);
TestBigIntForEverythingWorksGeneric<long>((long)1, dbType);
TestBigIntForEverythingWorksGeneric<ulong>((ulong)1, dbType);
TestBigIntForEverythingWorksGeneric<float>((float)1, dbType);
TestBigIntForEverythingWorksGeneric<double>((double)1, dbType);
TestBigIntForEverythingWorksGeneric<decimal>((decimal)1, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Byte.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_SByte.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Int.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_UInt.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Short.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_UShort.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_Long.B, dbType);
TestBigIntForEverythingWorksGeneric(LotsOfNumerics.E_ULong.B, dbType);
TestBigIntForEverythingWorksGeneric<bool?>(true, dbType);
TestBigIntForEverythingWorksGeneric<sbyte?>((sbyte)1, dbType);
TestBigIntForEverythingWorksGeneric<byte?>((byte)1, dbType);
TestBigIntForEverythingWorksGeneric<int?>((int)1, dbType);
TestBigIntForEverythingWorksGeneric<uint?>((uint)1, dbType);
TestBigIntForEverythingWorksGeneric<short?>((short)1, dbType);
TestBigIntForEverythingWorksGeneric<ushort?>((ushort)1, dbType);
TestBigIntForEverythingWorksGeneric<long?>((long)1, dbType);
TestBigIntForEverythingWorksGeneric<ulong?>((ulong)1, dbType);
TestBigIntForEverythingWorksGeneric<float?>((float)1, dbType);
TestBigIntForEverythingWorksGeneric<double?>((double)1, dbType);
TestBigIntForEverythingWorksGeneric<decimal?>((decimal)1, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Byte?>(LotsOfNumerics.E_Byte.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_SByte?>(LotsOfNumerics.E_SByte.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Int?>(LotsOfNumerics.E_Int.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_UInt?>(LotsOfNumerics.E_UInt.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Short?>(LotsOfNumerics.E_Short.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_UShort?>(LotsOfNumerics.E_UShort.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_Long?>(LotsOfNumerics.E_Long.B, dbType);
TestBigIntForEverythingWorksGeneric<LotsOfNumerics.E_ULong?>(LotsOfNumerics.E_ULong.B, dbType);
}
private void TestBigIntForEverythingWorksGeneric<T>(T expected, string dbType)
{
var query = connection.Query<T>("select cast(1 as " + dbType + ")").Single();
query.IsEqualTo(expected);
Assert.Equal(query, expected);
var scalar = connection.ExecuteScalar<T>("select cast(1 as " + dbType + ")");
scalar.IsEqualTo(expected);
Assert.Equal(scalar, expected);
}
[Fact]
public void TestSubsequentQueriesSuccess()
{
var data0 = connection.Query<Fooz0>("select 1 as [Id] where 1 = 0").ToList();
data0.Count.IsEqualTo(0);
Assert.Empty(data0);
var data1 = connection.Query<Fooz1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ToList();
data1.Count.IsEqualTo(0);
Assert.Empty(data1);
var data2 = connection.Query<Fooz2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ToList();
data2.Count.IsEqualTo(0);
Assert.Empty(data2);
data0 = connection.Query<Fooz0>("select 1 as [Id] where 1 = 0").ToList();
data0.Count.IsEqualTo(0);
Assert.Empty(data0);
data1 = connection.Query<Fooz1>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.Buffered)).ToList();
data1.Count.IsEqualTo(0);
Assert.Empty(data1);
data2 = connection.Query<Fooz2>(new CommandDefinition("select 1 as [Id] where 1 = 0", flags: CommandFlags.None)).ToList();
data2.Count.IsEqualTo(0);
Assert.Empty(data2);
}
private class Fooz0
......@@ -365,8 +411,8 @@ public void SO24740733_TestCustomValueHandler()
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);
Assert.Equal("Foo", foo.CategoryName);
Assert.Equal(200, foo.CategoryRating.Value);
}
[Fact]
......@@ -375,7 +421,7 @@ public void SO24740733_TestCustomValueSingleColumn()
SqlMapper.AddTypeHandler(RatingValueHandler.Default);
var foo = connection.Query<RatingValue>("SELECT 200 AS CategoryRating").Single();
foo.Value.IsEqualTo(200);
Assert.Equal(200, foo.Value);
}
public class StringListTypeHandler : SqlMapper.TypeHandler<List<String>>
......@@ -408,7 +454,7 @@ public void Issue253_TestIEnumerableTypeHandlerParsing()
SqlMapper.ResetTypeHandlers();
SqlMapper.AddTypeHandler(StringListTypeHandler.Default);
var foo = connection.Query<MyObjectWithStringList>("SELECT 'Sam,Kyro' AS Names").Single();
foo.Names.IsSequenceEqualTo(new[] { "Sam", "Kyro" });
Assert.Equal(new[] { "Sam", "Kyro" }, foo.Names);
}
[Fact]
......@@ -423,7 +469,7 @@ public void Issue253_TestIEnumerableTypeHandlerSetParameterValue()
const 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);
Assert.Equal(foo, names);
}
finally
{
......@@ -462,11 +508,11 @@ public void Test_RemoveTypeMap()
try
{
connection.Execute(@"INSERT INTO #Test_RemoveTypeMap VALUES (@Now)", new { DateTime.Now });
connection.Execute("INSERT INTO #Test_RemoveTypeMap VALUES (@Now)", new { DateTime.Now });
connection.Query<DateTime>("SELECT * FROM #Test_RemoveTypeMap");
dateTimeHandler.ParseWasCalled.IsTrue();
dateTimeHandler.SetValueWasCalled.IsTrue();
Assert.True(dateTimeHandler.ParseWasCalled);
Assert.True(dateTimeHandler.SetValueWasCalled);
}
finally
{
......@@ -483,27 +529,27 @@ public void TestReaderWhenResultsChange()
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);
Assert.Equal(1, obj1.X);
Assert.Equal(0, obj1.Y);
Assert.Equal(0, obj1.Z);
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);
Assert.Equal(1, obj2.X);
Assert.Equal(1, obj2.Y);
Assert.Equal(0, obj2.Z);
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);
Assert.Equal(1, obj3.X);
Assert.Equal(0, obj3.Y);
Assert.Equal(2, obj3.Z);
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);
Assert.Equal(1, obj4.X);
Assert.Equal(1, obj4.Y);
Assert.Equal(2, obj4.Z);
}
finally
{
......@@ -518,51 +564,6 @@ private class ResultsChangeType
public int Z { get; set; }
}
[Fact]
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
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping),
(type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
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
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");
}
private static string GetDescriptionFromAttribute(MemberInfo member)
{
if (member == null) return null;
#if COREFX
var data = member.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(DescriptionAttribute));
return (string)data?.ConstructorArguments.Single().Value;
#else
var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
return attrib?.Description;
#endif
}
public class TypeWithMapping
{
[Description("B")]
public string A { get; set; }
[Description("A")]
public string B { get; set; }
}
public class WrongTypes
{
public int A { get; set; }
......@@ -598,10 +599,10 @@ public void SO24607639_NullableBools()
@"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();
Assert.NotNull(obj);
Assert.True(obj.A.Value);
Assert.False(obj.B.Value);
Assert.Null(obj.C);
}
private class HazBools
......@@ -617,31 +618,22 @@ 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");
Assert.Equal(1, a);
Assert.Equal("2", b);
row = connection.Query<dynamic>("select 3 as [a], '4' as [b]").Single();
a = row.a;
b = row.b;
a.IsEqualTo(3);
b.IsEqualTo("4");
Assert.Equal(3, a);
Assert.Equal("4", b);
}
[Fact]
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;
}
catch (Exception ex)
{
error = ex.Message;
}
error.IsEqualTo("Error parsing column 0 (Id=cf0ef7ac-b6fe-4e24-aeda-a2b45bb5654e - Object)");
var ex = Assert.ThrowsAny<Exception>(() => connection.Query<Issue149_Person>("select @guid as Id", new { guid }).First());
Assert.Equal("Error parsing column 0 (Id=cf0ef7ac-b6fe-4e24-aeda-a2b45bb5654e - Object)", ex.Message);
}
public class Issue149_Person { public string Id { get; set; } }
......@@ -656,7 +648,86 @@ public void SO29343103_UtcDates()
var date = DateTime.UtcNow;
var returned = connection.Query<DateTime>(sql, new { date }).Single();
var delta = returned - date;
Assert.IsTrue(delta.TotalMilliseconds >= -10 && delta.TotalMilliseconds <= 10);
Assert.True(delta.TotalMilliseconds >= -10 && delta.TotalMilliseconds <= 10);
}
[Fact]
public void Issue461_TypeHandlerWorksInConstructor()
{
SqlMapper.AddTypeHandler(new Issue461_BlargHandler());
connection.Execute(@"CREATE TABLE #Issue461 (
Id int not null IDENTITY(1,1),
SomeValue nvarchar(50),
SomeBlargValue nvarchar(200),
)");
const string Expected = "abc123def";
var blarg = new Blarg(Expected);
connection.Execute(
"INSERT INTO #Issue461 (SomeValue, SomeBlargValue) VALUES (@value, @blarg)",
new { value = "what up?", blarg });
// test: without constructor
var parameterlessWorks = connection.QuerySingle<Issue461_ParameterlessTypeConstructor>("SELECT * FROM #Issue461");
Assert.Equal(1, parameterlessWorks.Id);
Assert.Equal("what up?", parameterlessWorks.SomeValue);
Assert.Equal(parameterlessWorks.SomeBlargValue.Value, Expected);
// test: via constructor
var parameterDoesNot = connection.QuerySingle<Issue461_ParameterisedTypeConstructor>("SELECT * FROM #Issue461");
Assert.Equal(1, parameterDoesNot.Id);
Assert.Equal("what up?", parameterDoesNot.SomeValue);
Assert.Equal(parameterDoesNot.SomeBlargValue.Value, Expected);
}
// I would usually expect this to be a struct; using a class
// so that we can't pass unexpectedly due to forcing an unsafe cast - want
// to see an InvalidCastException if it is wrong
private class Blarg
{
public Blarg(string value) { Value = value; }
public string Value { get; }
public override string ToString()
{
return Value;
}
}
private class Issue461_BlargHandler : SqlMapper.TypeHandler<Blarg>
{
public override void SetValue(IDbDataParameter parameter, Blarg value)
{
parameter.Value = ((object)value.Value) ?? DBNull.Value;
}
public override Blarg Parse(object value)
{
string s = (value == null || value is DBNull) ? null : Convert.ToString(value);
return new Blarg(s);
}
}
private class Issue461_ParameterlessTypeConstructor
{
public int Id { get; set; }
public string SomeValue { get; set; }
public Blarg SomeBlargValue { get; set; }
}
private class Issue461_ParameterisedTypeConstructor
{
public Issue461_ParameterisedTypeConstructor(int id, string someValue, Blarg someBlargValue)
{
Id = id;
SomeValue = someValue;
SomeBlargValue = someBlargValue;
}
public int Id { get; }
public string SomeValue { get; }
public Blarg SomeBlargValue { get; }
}
}
}
......@@ -19,9 +19,9 @@ public void CommonXmlTypesSupported()
C = XElement.Parse("<ghi/>")
};
var bar = connection.QuerySingle<Foo>("select @a as [A], @b as [B], @c as [C]", new { a = foo.A, b = foo.B, c = foo.C });
bar.A.DocumentElement.Name.IsEqualTo("abc");
bar.B.Root.Name.LocalName.IsEqualTo("def");
bar.C.Name.LocalName.IsEqualTo("ghi");
Assert.Equal("abc", bar.A.DocumentElement.Name);
Assert.Equal("def", bar.B.Root.Name.LocalName);
Assert.Equal("ghi", bar.C.Name.LocalName);
}
public class Foo
......

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
VisualStudioVersion = 15.0.26730.8
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A34907DF-958A-4E4C-8491-84CF303FD13E}"
ProjectSection(SolutionItems) = preProject
appveyor.yml = appveyor.yml
build.ps1 = build.ps1
build.sh = build.sh
Directory.build.props = Directory.build.props
License.txt = License.txt
nuget.config = nuget.config
Readme.md = Readme.md
semver.txt = semver.txt
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Dapper", "Dapper\Dapper.csproj", "{FAC24C3F-68F9-4247-A4B9-21D487E99275}"
......@@ -101,4 +103,7 @@ Global
{39D3EEB6-9C05-4F4A-8C01-7B209742A7EB} = {4E956F6B-6BD8-46F5-BC85-49292FF8F9AB}
{F017075A-2969-4A8E-8971-26F154EB420F} = {568BD46C-1C65-4D44-870C-12CD72563262}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {928A4226-96F3-409A-8A83-9E7444488710}
EndGlobalSection
EndGlobal
......@@ -5,9 +5,9 @@
<Title>Dapper</Title>
<Description>A high performance Micro-ORM supporting SQL Server, MySQL, Sqlite, SqlCE, Firebird etc..</Description>
<Authors>Sam Saffron;Marc Gravell;Nick Craver</Authors>
<TargetFrameworks>net40;net45;net451;netstandard1.3</TargetFrameworks>
<TargetFrameworks>net451;netstandard1.3;netstandard2.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' OR '$(TargetFramework)' == 'net451' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net451'">
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
......@@ -17,7 +17,7 @@
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<PackageReference Include="System.Collections.Concurrent" Version="4.3.0" />
<PackageReference Include="System.Collections.NonGeneric" Version="4.3.0" />
<PackageReference Include="System.Data.Common" Version="4.3.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.3.0" />
<PackageReference Include="System.Dynamic.Runtime" Version="4.3.0" />
<PackageReference Include="System.Reflection.Emit" Version="4.3.0" />
<PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" />
......@@ -25,4 +25,9 @@
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
<PackageReference Include="System.Reflection.Emit.Lightweight" Version="4.3.0" />
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.4.0" />
</ItemGroup>
</Project>
using System;
using System.Data;
#if !COREFX
#if !NETSTANDARD1_3
namespace Dapper
{
internal sealed class DataTableHandler : SqlMapper.ITypeHandler
......
......@@ -55,8 +55,18 @@ public void AddParameter(IDbCommand command, string name)
{
throw new InvalidOperationException("If specifying IsFixedLength, a Length must also be specified");
}
var param = command.CreateParameter();
bool add = !command.Parameters.Contains(name);
IDbDataParameter param;
if (add)
{
param = command.CreateParameter();
param.ParameterName = name;
}
else
{
param = (IDbDataParameter)command.Parameters[name];
}
#pragma warning disable 0618
param.Value = SqlMapper.SanitizeParameterValue(Value);
#pragma warning restore 0618
......@@ -69,7 +79,10 @@ public void AddParameter(IDbCommand command, string name)
param.Size = Length;
}
param.DbType = IsAnsi ? (IsFixedLength ? DbType.AnsiStringFixedLength : DbType.AnsiString) : (IsFixedLength ? DbType.StringFixedLength : DbType.String);
if (add)
{
command.Parameters.Add(param);
}
}
}
}
......@@ -26,7 +26,7 @@ public DefaultTypeMap(Type type)
Properties = GetSettableProps(type);
_type = type;
}
#if COREFX
#if NETSTANDARD1_3
private static bool IsParameterMatch(ParameterInfo[] x, ParameterInfo[] y)
{
if (ReferenceEquals(x, y)) return true;
......@@ -40,7 +40,7 @@ private static bool IsParameterMatch(ParameterInfo[] x, ParameterInfo[] y)
internal static MethodInfo GetPropertySetter(PropertyInfo propertyInfo, Type type)
{
if (propertyInfo.DeclaringType == type) return propertyInfo.GetSetMethod(true);
#if COREFX
#if NETSTANDARD1_3
return propertyInfo.DeclaringType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Single(x => x.Name == propertyInfo.Name
&& x.PropertyType == propertyInfo.PropertyType
......@@ -118,7 +118,7 @@ public ConstructorInfo FindConstructor(string[] names, Type[] types)
public ConstructorInfo FindExplicitConstructor()
{
var constructors = _type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
#if COREFX
#if NETSTANDARD1_3
var withAttr = constructors.Where(c => c.CustomAttributes.Any(x => x.AttributeType == typeof(ExplicitConstructorAttribute))).ToList();
#else
var withAttr = constructors.Where(c => c.GetCustomAttributes(typeof(ExplicitConstructorAttribute), true).Length > 0).ToList();
......
......@@ -6,7 +6,7 @@
using System.Reflection;
using System.Reflection.Emit;
#if COREFX
#if NETSTANDARD1_3
using ApplicationException = System.InvalidOperationException;
#endif
......@@ -343,7 +343,7 @@ public DynamicParameters Output<T>(T target, Expression<Func<T, object>> express
{
var failMessage = "Expression must be a property/field chain off of a(n) {0} instance";
failMessage = string.Format(failMessage, typeof(T).Name);
Action @throw = () => { throw new InvalidOperationException(failMessage); };
Action @throw = () => throw new InvalidOperationException(failMessage);
// Is it even a MemberExpression?
var lastMemberAccess = expression.Body as MemberExpression;
......
......@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Data;
#if !COREFX
namespace Dapper
{
internal sealed class SqlDataRecordHandler : SqlMapper.ITypeHandler
......@@ -18,4 +17,3 @@ public void SetValue(IDbDataParameter parameter, object value)
}
}
}
#endif
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
#if !COREFX
namespace Dapper
{
/// <summary>
......@@ -23,18 +22,6 @@ public SqlDataRecordListTVPParameter(IEnumerable<Microsoft.SqlServer.Server.SqlD
this.typeName = typeName;
}
private static readonly Action<System.Data.SqlClient.SqlParameter, string> setTypeName;
static SqlDataRecordListTVPParameter()
{
var prop = typeof(System.Data.SqlClient.SqlParameter).GetProperty(nameof(System.Data.SqlClient.SqlParameter.TypeName), BindingFlags.Instance | BindingFlags.Public);
if (prop != null && prop.PropertyType == typeof(string) && prop.CanWrite)
{
setTypeName = (Action<System.Data.SqlClient.SqlParameter, string>)
Delegate.CreateDelegate(typeof(Action<System.Data.SqlClient.SqlParameter, string>), prop.GetSetMethod());
}
}
void SqlMapper.ICustomQueryParameter.AddParameter(IDbCommand command, string name)
{
var param = command.CreateParameter();
......@@ -54,4 +41,3 @@ internal static void Set(IDbDataParameter parameter, IEnumerable<Microsoft.SqlSe
}
}
}
#endif
\ No newline at end of file
......@@ -140,6 +140,54 @@ public static partial class SqlMapper
public static Task<T> QuerySingleOrDefaultAsync<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
QueryRowAsync<T>(cnn, Row.SingleOrDefault, typeof(T), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken)));
/// <summary>
/// Execute a single-row query asynchronously using .NET 4.5 Task.
/// </summary>
/// <param name="cnn">The connection to query on.</param>
/// <param name="sql">The SQL to execute for the query.</param>
/// <param name="param">The parameters to pass, if any.</param>
/// <param name="transaction">The transaction to use, if any.</param>
/// <param name="commandTimeout">The command timeout (in seconds).</param>
/// <param name="commandType">The type of command to execute.</param>
public static Task<dynamic> QueryFirstAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
QueryRowAsync<dynamic>(cnn, Row.First, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken)));
/// <summary>
/// Execute a single-row query asynchronously using .NET 4.5 Task.
/// </summary>
/// <param name="cnn">The connection to query on.</param>
/// <param name="sql">The SQL to execute for the query.</param>
/// <param name="param">The parameters to pass, if any.</param>
/// <param name="transaction">The transaction to use, if any.</param>
/// <param name="commandTimeout">The command timeout (in seconds).</param>
/// <param name="commandType">The type of command to execute.</param>
public static Task<dynamic> QueryFirstOrDefaultAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
QueryRowAsync<dynamic>(cnn, Row.FirstOrDefault, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken)));
/// <summary>
/// Execute a single-row query asynchronously using .NET 4.5 Task.
/// </summary>
/// <param name="cnn">The connection to query on.</param>
/// <param name="sql">The SQL to execute for the query.</param>
/// <param name="param">The parameters to pass, if any.</param>
/// <param name="transaction">The transaction to use, if any.</param>
/// <param name="commandTimeout">The command timeout (in seconds).</param>
/// <param name="commandType">The type of command to execute.</param>
public static Task<dynamic> QuerySingleAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
QueryRowAsync<dynamic>(cnn, Row.Single, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken)));
/// <summary>
/// Execute a single-row query asynchronously using .NET 4.5 Task.
/// </summary>
/// <param name="cnn">The connection to query on.</param>
/// <param name="sql">The SQL to execute for the query.</param>
/// <param name="param">The parameters to pass, if any.</param>
/// <param name="transaction">The transaction to use, if any.</param>
/// <param name="commandTimeout">The command timeout (in seconds).</param>
/// <param name="commandType">The type of command to execute.</param>
public static Task<dynamic> QuerySingleOrDefaultAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
QueryRowAsync<dynamic>(cnn, Row.SingleOrDefault, typeof(DapperRow), new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.None, default(CancellationToken)));
/// <summary>
/// Execute a query asynchronously using .NET 4.5 Task.
/// </summary>
......@@ -1017,7 +1065,7 @@ public static async Task<GridReader> QueryMultipleAsync(this IDbConnection cnn,
/// </code>
/// </example>
public static Task<IDataReader> ExecuteReaderAsync(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) =>
ExecuteReaderImplAsync(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered));
ExecuteReaderImplAsync(cnn, new CommandDefinition(sql, param, transaction, commandTimeout, commandType, CommandFlags.Buffered), CommandBehavior.Default);
/// <summary>
/// Execute parameterized SQL and return an <see cref="IDataReader"/>.
......@@ -1030,9 +1078,23 @@ public static async Task<GridReader> QueryMultipleAsync(this IDbConnection cnn,
/// or <see cref="T:DataSet"/>.
/// </remarks>
public static Task<IDataReader> ExecuteReaderAsync(this IDbConnection cnn, CommandDefinition command) =>
ExecuteReaderImplAsync(cnn, command);
ExecuteReaderImplAsync(cnn, command, CommandBehavior.Default);
/// <summary>
/// Execute parameterized SQL and return an <see cref="IDataReader"/>.
/// </summary>
/// <param name="cnn">The connection to execute on.</param>
/// <param name="command">The command to execute.</param>
/// <param name="commandBehavior">The <see cref="CommandBehavior"/> flags for this reader.</param>
/// <returns>An <see cref="IDataReader"/> that can be used to iterate over the results of the SQL query.</returns>
/// <remarks>
/// This is typically used when the results of a query are not processed by Dapper, for example, used to fill a <see cref="DataTable"/>
/// or <see cref="T:DataSet"/>.
/// </remarks>
public static Task<IDataReader> ExecuteReaderAsync(this IDbConnection cnn, CommandDefinition command, CommandBehavior commandBehavior) =>
ExecuteReaderImplAsync(cnn, command, commandBehavior);
private static async Task<IDataReader> ExecuteReaderImplAsync(IDbConnection cnn, CommandDefinition command)
private static async Task<IDataReader> ExecuteReaderImplAsync(IDbConnection cnn, CommandDefinition command, CommandBehavior commandBehavior)
{
Action<IDbCommand, object> paramReader = GetParameterReader(cnn, ref command);
......@@ -1042,7 +1104,7 @@ private static async Task<IDataReader> ExecuteReaderImplAsync(IDbConnection cnn,
{
cmd = (DbCommand)command.SetupCommand(cnn, paramReader);
if (wasClosed) await ((DbConnection)cnn).OpenAsync(command.CancellationToken).ConfigureAwait(false);
var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.Default, command.CancellationToken).ConfigureAwait(false);
var reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, commandBehavior, command.CancellationToken).ConfigureAwait(false);
wasClosed = false;
return reader;
}
......
......@@ -11,7 +11,7 @@ public static partial class SqlMapper
/// </summary>
/// <typeparam name="T">The type to have a cache for.</typeparam>
[Obsolete(ObsoleteInternalUsageOnly, false)]
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......
......@@ -19,7 +19,7 @@
using System.Xml;
using System.Xml.Linq;
#if COREFX
#if NETSTANDARD1_3
using DataException = System.InvalidOperationException;
#endif
......@@ -221,26 +221,24 @@ static SqlMapper()
private static void ResetTypeHandlers(bool clone)
{
typeHandlers = new Dictionary<Type, ITypeHandler>();
#if !COREFX
#if !NETSTANDARD1_3
AddTypeHandlerImpl(typeof(DataTable), new DataTableHandler(), clone);
#endif
try
{
AddSqlDataRecordsTypeHandler(clone);
}
catch { /* https://github.com/StackExchange/dapper-dot-net/issues/424 */ }
#endif
AddTypeHandlerImpl(typeof(XmlDocument), new XmlDocumentHandler(), clone);
AddTypeHandlerImpl(typeof(XDocument), new XDocumentHandler(), clone);
AddTypeHandlerImpl(typeof(XElement), new XElementHandler(), clone);
}
#if !COREFX
[MethodImpl(MethodImplOptions.NoInlining)]
private static void AddSqlDataRecordsTypeHandler(bool clone)
{
AddTypeHandlerImpl(typeof(IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord>), new SqlDataRecordHandler(), clone);
}
#endif
/// <summary>
/// Configure the specified type to be mapped to a given db-type.
......@@ -352,7 +350,7 @@ public static void AddTypeHandlerImpl(Type type, ITypeHandler handler, bool clon
/// </summary>
/// <param name="value">The object to get a corresponding database type for.</param>
[Obsolete(ObsoleteInternalUsageOnly, false)]
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......@@ -371,7 +369,7 @@ public static DbType GetDbType(object value)
/// <param name="demand">Whether to demand a value (throw if missing).</param>
/// <param name="handler">The handler for <paramref name="type"/>.</param>
[Obsolete(ObsoleteInternalUsageOnly, false)]
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......@@ -401,7 +399,7 @@ public static DbType LookupDbType(Type type, string name, bool demand, out IType
return DynamicParameters.EnumerableMultiParameter;
}
#if !COREFX
#if !NETSTANDARD1_3 && !NETSTANDARD2_0
switch (type.FullName)
{
case "Microsoft.SqlServer.Types.SqlGeography":
......@@ -1868,7 +1866,7 @@ private static Exception MultiMapException(IDataRecord reader)
/// Internal use only.
/// </summary>
/// <param name="value">The object to convert to a character.</param>
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......@@ -1885,7 +1883,7 @@ public static char ReadChar(object value)
/// Internal use only.
/// </summary>
/// <param name="value">The object to convert to a character.</param>
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......@@ -1904,7 +1902,7 @@ public static char ReadChar(object value)
/// <param name="parameters">The parameter collection to search in.</param>
/// <param name="command">The command for this fetch.</param>
/// <param name="name">The name of the parameter to get.</param>
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......@@ -1954,7 +1952,7 @@ internal static int GetListPaddingExtraCount(int count)
private static string GetInListRegex(string name, bool byPosition) => byPosition
? (@"(\?)" + Regex.Escape(name) + @"\?(?!\w)(\s+(?i)unknown(?-i))?")
: (@"([?@:]" + Regex.Escape(name) + @")(?!\w)(\s+(?i)unknown(?-i))?");
: ("([?@:]" + Regex.Escape(name) + @")(?!\w)(\s+(?i)unknown(?-i))?");
/// <summary>
/// Internal use only.
......@@ -1962,7 +1960,7 @@ internal static int GetListPaddingExtraCount(int count)
/// <param name="command">The command to pack parameters for.</param>
/// <param name="namePrefix">The name prefix for these parameters.</param>
/// <param name="value">The parameter value can be an <see cref="IEnumerable{T}"/></param>
#if !COREFX
#if !NETSTANDARD1_3
[Browsable(false)]
#endif
[EditorBrowsable(EditorBrowsableState.Never)]
......@@ -2267,7 +2265,7 @@ public static string Format(object value)
{
switch (TypeExtensions.GetTypeCode(value.GetType()))
{
#if !COREFX
#if !NETSTANDARD1_3
case TypeCode.DBNull:
return "null";
#endif
......@@ -3102,7 +3100,7 @@ private static LocalBuilder GetTempLocal(ILGenerator il, ref Dictionary<Type, Lo
int index = startBound;
ConstructorInfo specializedConstructor = null;
#if !COREFX
#if !NETSTANDARD1_3
bool supportInitialize = false;
#endif
Dictionary<Type, LocalBuilder> structLocals = null;
......@@ -3137,7 +3135,7 @@ private static LocalBuilder GetTempLocal(ILGenerator il, ref Dictionary<Type, Lo
il.Emit(OpCodes.Newobj, explicitConstr);
il.Emit(OpCodes.Stloc_1);
#if !COREFX
#if !NETSTANDARD1_3
supportInitialize = typeof(ISupportInitialize).IsAssignableFrom(type);
if (supportInitialize)
{
......@@ -3159,7 +3157,7 @@ private static LocalBuilder GetTempLocal(ILGenerator il, ref Dictionary<Type, Lo
{
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_1);
#if !COREFX
#if !NETSTANDARD1_3
supportInitialize = typeof(ISupportInitialize).IsAssignableFrom(type);
if (supportInitialize)
{
......@@ -3376,7 +3374,7 @@ private static LocalBuilder GetTempLocal(ILGenerator il, ref Dictionary<Type, Lo
il.Emit(OpCodes.Newobj, specializedConstructor);
}
il.Emit(OpCodes.Stloc_1); // stack is empty
#if !COREFX
#if !NETSTANDARD1_3
if (supportInitialize)
{
il.Emit(OpCodes.Ldloc_1);
......@@ -3648,7 +3646,7 @@ public static IEqualityComparer<string> ConnectionStringComparer
private static IEqualityComparer<string> connectionStringComparer = StringComparer.Ordinal;
#if !COREFX
#if !NETSTANDARD1_3
/// <summary>
/// Key used to indicate the type name associated with a DataTable.
/// </summary>
......@@ -3684,15 +3682,15 @@ public static void SetTypeName(this DataTable table, string typeName)
/// <param name="table">The <see cref="DataTable"/> that has a type name associated with it.</param>
public static string GetTypeName(this DataTable table) =>
table?.ExtendedProperties[DataTableTypeNameKey] as string;
#endif
/// <summary>
/// Used to pass a IEnumerable&lt;SqlDataRecord&gt; as a <see cref="TableValuedParameter"/>.
/// Used to pass a IEnumerable&lt;SqlDataRecord&gt; as a TableValuedParameter.
/// </summary>
/// <param name="list">Thhe list of records to convert to TVPs.</param>
/// <param name="list">The list of records to convert to TVPs.</param>
/// <param name="typeName">The sql parameter type name.</param>
public static ICustomQueryParameter AsTableValuedParameter(this IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> list, string typeName = null) =>
new SqlDataRecordListTVPParameter(list, typeName);
#endif
// one per thread
[ThreadStatic]
......
......@@ -2,7 +2,7 @@
using System.Data;
using System.Reflection;
#if !COREFX
#if !NETSTANDARD1_3
namespace Dapper
{
/// <summary>
......
......@@ -7,41 +7,41 @@ namespace Dapper
internal static class TypeExtensions
{
public static string Name(this Type type) =>
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().Name;
#else
type.Name;
#endif
public static bool IsValueType(this Type type) =>
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsValueType;
#else
type.IsValueType;
#endif
public static bool IsEnum(this Type type) =>
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsEnum;
#else
type.IsEnum;
#endif
public static bool IsGenericType(this Type type) =>
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsGenericType;
#else
type.IsGenericType;
#endif
public static bool IsInterface(this Type type) =>
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsInterface;
#else
type.IsInterface;
#endif
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
public static IEnumerable<Attribute> GetCustomAttributes(this Type type, bool inherit)
{
return type.GetTypeInfo().GetCustomAttributes(inherit);
......@@ -85,7 +85,7 @@ public static TypeCode GetTypeCode(Type type)
public static MethodInfo GetPublicInstanceMethod(this Type type, string name, Type[] types)
{
#if COREFX
#if NETSTANDARD1_3 || NETCOREAPP1_0
var method = type.GetMethod(name, types);
return (method?.IsPublic == true && !method.IsStatic) ? method : null;
#else
......
......@@ -5,7 +5,7 @@ namespace Dapper
{
public static partial class SqlMapper
{
#if !COREFX
#if !NETSTANDARD1_3 && !NETSTANDARD2_0
/// <summary>
/// A type handler for data-types that are supported by the underlying provider, but which need
/// a well-known UdtTypeName to be specified
......
......@@ -19,28 +19,20 @@
<DebugType>embedded</DebugType>
<DefaultLanguage>en-US</DefaultLanguage>
<IncludeSymbols>false</IncludeSymbols>
<xUnitVersion>2.3.0-beta5-build3750</xUnitVersion>
</PropertyGroup>
<!-- Workarounds for https://github.com/NuGet/Home/issues/4853 -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' OR '$(TargetFramework)' == 'net451'">
<DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
<AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net40' OR '$(TargetFramework)' == 'net45' OR '$(TargetFramework)' == 'net451'">
<Reference Include="System.Core" Pack="false" />
</ItemGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'net45' OR '$(TargetFramework)' == 'net451'">
<PropertyGroup Condition=" '$(TargetFramework)' != 'net40'">
<DefineConstants>$(DefineConstants);ASYNC</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<DefineConstants>$(DefineConstants);ASYNC;COREFX</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SourceLink.Create.GitHub" Version="2.0.2" PrivateAssets="All" />
<PackageReference Include="NuGet.Build.Tasks.Pack" Version="4.3.0-preview1-4045" PrivateAssets="All" />
<DotNetCliToolReference Include="dotnet-sourcelink" Version="2.0.2" />
<DotNetCliToolReference Include="dotnet-sourcelink-git" Version="2.0.2" />
<PackageReference Include="SourceLink.Create.GitHub" Version="2.1.2" PrivateAssets="All" />
<DotNetCliToolReference Include="dotnet-sourcelink" Version="2.1.2" />
<DotNetCliToolReference Include="dotnet-sourcelink-git" Version="2.1.2" />
</ItemGroup>
</Project>
\ No newline at end of file
......@@ -36,14 +36,9 @@ public class Dog
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
dog.Count()
.IsEqualTo(1);
dog.First().Age
.IsNull();
dog.First().Id
.IsEqualTo(guid);
Assert.Equal(1,dog.Count());
Assert.Null(dog.First().Age);
Assert.Equal(guid, dog.First().Id);
```
Execute a query and map it to a list of dynamic objects
......@@ -59,17 +54,10 @@ Example usage:
```csharp
var rows = connection.Query("select 1 A, 2 B union all select 3, 4");
((int)rows[0].A)
.IsEqualTo(1);
((int)rows[0].B)
.IsEqualTo(2);
((int)rows[1].A)
.IsEqualTo(3);
((int)rows[1].B)
.IsEqualTo(4);
Assert.Equal(1, (int)rows[0].A);
Assert.Equal(2, (int)rows[0].B);
Assert.Equal(3, (int)rows[1].A);
Assert.Equal(4, (int)rows[1].B);
```
Execute a Command that returns no results
......@@ -82,15 +70,15 @@ public static int Execute(this IDbConnection cnn, string sql, object param = nul
Example usage:
```csharp
connection.Execute(@"
var count = connection.Execute(@"
set nocount on
create table #t(i int)
set nocount off
insert #t
select @a a union all select @b
set nocount on
drop table #t", new {a=1, b=2 })
.IsEqualTo(2);
drop table #t", new {a=1, b=2 });
Assert.Equal(2, count);
```
Execute a Command multiple times
......@@ -101,9 +89,10 @@ The same signature also allows you to conveniently and efficiently execute a com
Example usage:
```csharp
connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
var count = connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
).IsEqualTo(3); // 3 rows inserted: "1,1", "2,2" and "3,3"
);
Assert.Equal(3, count); // 3 rows inserted: "1,1", "2,2" and "3,3"
```
This works for any parameter that implements IEnumerable<T> for some T.
......@@ -240,10 +229,10 @@ Order by p.Id";
var data = connection.Query<Post, User, Post>(sql, (post, user) => { post.Owner = user; return post;});
var post = data.First();
post.Content.IsEqualTo("Sams Post1");
post.Id.IsEqualTo(1);
post.Owner.Name.IsEqualTo("Sam");
post.Owner.Id.IsEqualTo(99);
Assert.Equal("Sams Post1", post.Content);
Assert.Equal(1, post.Id);
Assert.Equal("Sam", post.Owner.Name);
Assert.Equal(99, post.Owner.Id);
```
Dapper is able to split the returned row by making an assumption that your Id columns are named `Id` or `id`. If your primary key is different or you would like to split the row at a point other than `Id`, use the optional `splitOn` parameter.
......@@ -363,8 +352,4 @@ Dapper has a comprehensive test suite in the [test project](https://github.com/S
Who is using this?
---------------------
Dapper is in production use at:
[Stack Overflow](https://stackoverflow.com/), [helpdesk](https://www.jitbit.com/web-helpdesk/)
(if you would like to be listed here let me know)
Dapper is in production use at [Stack Overflow](https://stackoverflow.com/).
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="xUnit" value="https://www.myget.org/F/xunit/api/v3/index.json" />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
\ No newline at end of file
1.50.3-alpha1
\ No newline at end of file
1.50.4-alpha1
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment