Skip to content

Commit

Permalink
Fixes for issue DapperLib#351
Browse files Browse the repository at this point in the history
  • Loading branch information
johandanforth committed Oct 13, 2015
1 parent 3081cd7 commit 2f7125a
Show file tree
Hide file tree
Showing 19 changed files with 765 additions and 60 deletions.
52 changes: 27 additions & 25 deletions Dapper.Contrib NET45/SqlMapperExtensionsAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public static async Task<T> GetAsync<T>(this IDbConnection connection, dynamic i
foreach (var property in TypePropertiesCache(type))
{
var val = res[property.Name];
property.SetValue(obj, val, null);
property.SetValue(obj, Convert.ChangeType(val, property.PropertyType), null);
}

((IProxy)obj).IsDirty = false; //reset change tracking and return
Expand Down Expand Up @@ -114,7 +114,7 @@ public static async Task<IEnumerable<T>> GetAllAsync<T>(this IDbConnection conne
foreach (var property in TypePropertiesCache(type))
{
var val = res[property.Name];
property.SetValue(obj, val, null);
property.SetValue(obj, Convert.ChangeType(val, property.PropertyType), null);
}
((IProxy)obj).IsDirty = false; //reset change tracking and return
list.Add(obj);
Expand Down Expand Up @@ -200,15 +200,17 @@ public static async Task<bool> UpdateAsync<T>(this IDbConnection connection, T e
type = type.GetGenericArguments()[0];

var keyProperties = KeyPropertiesCache(type);
if (!keyProperties.Any())
throw new ArgumentException("Entity must have at least one [Key] property");
var explicitKeyProperties = ExplicitKeyPropertiesCache(type);
if (!keyProperties.Any() && !explicitKeyProperties.Any())
throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");

var name = GetTableName(type);

var sb = new StringBuilder();
sb.AppendFormat("update {0} set ", name);

var allProperties = TypePropertiesCache(type);
keyProperties.AddRange(explicitKeyProperties);
var computedProperties = ComputedPropertiesCache(type);
var nonIdProps = allProperties.Except(keyProperties.Union(computedProperties)).ToList();

Expand Down Expand Up @@ -249,10 +251,12 @@ public static async Task<bool> DeleteAsync<T>(this IDbConnection connection, T e
type = type.GetGenericArguments()[0];

var keyProperties = KeyPropertiesCache(type);
if (!keyProperties.Any())
throw new ArgumentException("Entity must have at least one [Key] property");
var explicitKeyProperties = ExplicitKeyPropertiesCache(type);
if (!keyProperties.Any() && !explicitKeyProperties.Any())
throw new ArgumentException("Entity must have at least one [Key] or [ExplicitKey] property");

var name = GetTableName(type);
keyProperties.AddRange(explicitKeyProperties);

var sb = new StringBuilder();
sb.AppendFormat("delete from {0} where ", name);
Expand Down Expand Up @@ -294,11 +298,13 @@ public partial class SqlServerAdapter
{
public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{

var cmd = String.Format("insert into {0} ({1}) values ({2});select SCOPE_IDENTITY() id", tableName, columnList, parameterList);
var multi = await connection.QueryMultipleAsync(cmd, entityToInsert, transaction, commandTimeout);

var id = (int)multi.Read().First().id;
var first = multi.Read().FirstOrDefault();
if (first == null || first.id == null) return 0;

var id = (int)first.id;
var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
if (!propertyInfos.Any()) return id;

Expand All @@ -308,16 +314,6 @@ public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction tran
else
idProperty.SetValue(entityToInsert, id, null);
return id;

//var cmd = String.Format("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList);
//await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false);
//var r = await connection.QueryAsync<dynamic>("select SCOPE_IDENTITY() id", transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false);

//var id = (int)r.First().id;
//var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
//if (propertyInfos.Any())
// propertyInfos.First().SetValue(entityToInsert, id, null);
//return id;
}
}

Expand All @@ -326,15 +322,21 @@ public partial class SqlCeServerAdapter
public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert)
{
var cmd = String.Format("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList);

await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false);

var r = await connection.QueryAsync<dynamic>("select @@IDENTITY id", transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false);
var id = (int)r.First().id;
var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
if (propertyInfos.Any())
propertyInfos.First().SetValue(entityToInsert, id, null);
return id;

var id = r.First().id;
if (id == null) return 0;
var keyPropertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray();
if (keyPropertyInfos.Any())
{
var idProperty = keyPropertyInfos.First();
if (idProperty.PropertyType.Name == "Int16") //for short id/key types issue #196
idProperty.SetValue(entityToInsert, (Int16)id, null);
else
idProperty.SetValue(entityToInsert, (int)id, null);
}
return (int)id;
}
}

Expand Down
6 changes: 6 additions & 0 deletions Dapper.Contrib.MsSqlTests NET45/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E5482A3B-2C2A-4907-9804-C191F18FA622}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Dapper.Contrib.Tests</RootNamespace>
<AssemblyName>Dapper.Contrib.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;MSSQL</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Dapper.Contrib.Tests NET45\TestsAsync.cs">
<Link>TestsAsync.cs</Link>
</Compile>
<Compile Include="..\Dapper.Contrib.Tests\Assert.cs">
<Link>Assert.cs</Link>
</Compile>
<Compile Include="..\Dapper.Contrib.Tests\Tests.cs">
<Link>Tests.cs</Link>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dapper NET45\Dapper NET45.csproj">
<Project>{0fff5bc7-0a4b-4d87-835e-4fad70937507}</Project>
<Name>Dapper NET45</Name>
</ProjectReference>
<ProjectReference Include="..\Dapper.Contrib NET45\Dapper.Contrib NET45.csproj">
<Project>{302ec82f-a81b-48c5-b653-b5c75d2bd103}</Project>
<Name>Dapper.Contrib NET45</Name>
</ProjectReference>
<ProjectReference Include="..\Dapper.SqlBuilder\Dapper.SqlBuilder.csproj">
<Project>{bf782ef1-2b0f-42fa-9dd0-928454a94c6d}</Project>
<Name>Dapper.SqlBuilder</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
98 changes: 98 additions & 0 deletions Dapper.Contrib.MsSqlTests NET45/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Dapper.Contrib.Tests
{
class Program
{
static void Main(string[] args)
{
SetupMsSqlDatabase();
SetupTables();
RunTests();
DropTables();
SetupTables();
RunAsyncTests();
Console.WriteLine("Press any key...");
Console.ReadKey();
}

private static void SetupMsSqlDatabase()
{
using (var connection = new SqlConnection("Data Source = .\\SQLEXPRESS;Initial Catalog=master;Integrated Security=SSPI"))
{
connection.Open();
var exists = connection.Query<int>("SELECT count(*) FROM master.sys.databases WHERE name = @name",
new { name = "DapperContribMsSqlTests" }).First();
if (exists > 0)
{
connection.Execute("drop database DapperContribMsSqlTests");
}
connection.Execute("create database DapperContribMsSqlTests");

}
}

private static void DropTables()
{

using (var connection = new SqlConnection("Data Source = .\\SQLEXPRESS;Initial Catalog=DapperContribMsSqlTests;Integrated Security=SSPI"))
{
connection.Open();
connection.Execute("alter database DapperContribMsSqlTests set single_user with rollback immediate");
connection.Execute(@" drop table Stuff");
connection.Execute(@" drop table People ");
connection.Execute(@" drop table Users");
connection.Execute(@" drop table Automobiles ");
connection.Execute(@" drop table Results ");
connection.Execute(@" drop table ObjectX ");
connection.Execute(@" drop table ObjectY ");
}
Console.WriteLine("Created database");
}

private static void SetupTables()
{

using (var connection = new SqlConnection("Data Source = .\\SQLEXPRESS;Initial Catalog=DapperContribMsSqlTests;Integrated Security=SSPI"))
{
connection.Open();
connection.Execute(@" create table Stuff (TheId int IDENTITY(1,1) not null, Name nvarchar(100) not null, Created DateTime null) ");
connection.Execute(@" create table People (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null) ");
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 Automobiles (Id int IDENTITY(1,1) not null, Name nvarchar(100) not null) ");
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 ObjectX (ObjectXId nvarchar(100) not null, Name nvarchar(100) not null) ");
connection.Execute(@" create table ObjectY (ObjectYId int not null, Name nvarchar(100) not null) ");
}
Console.WriteLine("Created database");
}

private static void RunTests()
{
var tester = new Tests();
foreach (var method in typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Console.Write("Running " + method.Name);
method.Invoke(tester, null);
Console.WriteLine(" - OK!");
}
}

private static void RunAsyncTests()
{
var tester = new TestsAsync();
foreach (var method in typeof(TestsAsync).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Console.Write("Running " + method.Name);
Task.WaitAll((Task)method.Invoke(tester, null));
Console.WriteLine(" - OK!");
}
}
}
}
36 changes: 36 additions & 0 deletions Dapper.Contrib.MsSqlTests NET45/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dapper.Contrib.Tests NET45")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dapper.Contrib.Tests NET45")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d6cdd3d-b94b-4cd4-842a-60c6e4c93c5c")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Loading

0 comments on commit 2f7125a

Please sign in to comment.