Skip to content

Commit

Permalink
Added automatic casting for PostgreSQL JSON based on the presence of …
Browse files Browse the repository at this point in the history
…[JsonColumn] property attribute
  • Loading branch information
yasikovsky committed Jul 13, 2021
1 parent 44c34d5 commit 97e532d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Dapper.SimpleCRUD/Dapper.SimpleCRUD.csproj
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>2.1.0</Version>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
Expand Down
10 changes: 10 additions & 0 deletions Dapper.SimpleCRUD/JsonColumnAttribute.cs
@@ -0,0 +1,10 @@
using System;

namespace Dapper
{
[AttributeUsage(AttributeTargets.Property)]
public class JsonColumnAttribute : Attribute
{

}
}
20 changes: 18 additions & 2 deletions Dapper.SimpleCRUD/SimpleCRUD.cs
Expand Up @@ -714,7 +714,15 @@ private static void BuildUpdateSet<T>(T entityToUpdate, StringBuilder masterSb)
{
var property = nonIdProps[i];
sb.AppendFormat("{0} = @{1}", GetColumnName(property), property.Name);
if (_dialect == Dialect.PostgreSQL && property.GetCustomAttributes(true).Any(attr =>
attr.GetType().Name == nameof(JsonColumnAttribute)))
{
sb.AppendFormat("{0} = @{1}::json", GetColumnName(property), property.Name);
}
else {
sb.AppendFormat("{0} = @{1}", GetColumnName(property), property.Name);
}
if (i < nonIdProps.Length - 1)
sb.AppendFormat(", ");
}
Expand Down Expand Up @@ -806,7 +814,15 @@ private static void BuildInsertValues<T>(StringBuilder masterSb)
if (property.Name.Equals("Id", StringComparison.OrdinalIgnoreCase) && property.GetCustomAttributes(true).All(attr => attr.GetType().Name != typeof(RequiredAttribute).Name) && property.PropertyType != typeof(Guid)) continue;
sb.AppendFormat("@{0}", property.Name);
if (_dialect == Dialect.PostgreSQL && property.GetCustomAttributes(true).Any(attr =>
attr.GetType().Name == typeof(JsonColumnAttribute).Name))
{
sb.AppendFormat("@{0}::json", property.Name);
}
else {
sb.AppendFormat("@{0}", property.Name);
}
if (i < props.Count() - 1)
sb.Append(", ");
}
Expand Down

0 comments on commit 97e532d

Please sign in to comment.