Skip to content

Commit

Permalink
Respect [JsonPropertyName] in query translation
Browse files Browse the repository at this point in the history
  • Loading branch information
roji committed Jun 16, 2020
1 parent eda8129 commit 25c83d5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
Expand Down Expand Up @@ -28,7 +29,16 @@ public NpgsqlJsonPocoTranslator(
}

public virtual SqlExpression Translate(SqlExpression instance, MemberInfo member, Type returnType)
=> TranslateMemberAccess(instance, _sqlExpressionFactory.Constant(member.Name), returnType);
=> instance.TypeMapping is NpgsqlJsonTypeMapping || instance is PostgresJsonTraversalExpression
? TranslateMemberAccess(
instance,
_sqlExpressionFactory.Constant(
member.GetCustomAttribute<JsonPropertyNameAttribute>() is JsonPropertyNameAttribute
attribute
? attribute.Name
: member.Name),
returnType)
: null;

public virtual SqlExpression TranslateMemberAccess(
[NotNull] SqlExpression instance, [NotNull] SqlExpression member, [NotNull] Type returnType)
Expand Down
6 changes: 4 additions & 2 deletions test/EFCore.PG.FunctionalTests/Query/JsonPocoQueryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Npgsql.EntityFrameworkCore.PostgreSQL.TestUtilities;
Expand Down Expand Up @@ -70,7 +71,7 @@ public void Literal()
AssertSql(
@"SELECT j.""Id"", j.""Customer"", j.""ToplevelArray""
FROM ""JsonbEntities"" AS j
WHERE j.""Customer"" = '{""Name"":""Test customer"",""Age"":80,""ID"":""00000000-0000-0000-0000-000000000000"",""IsVip"":false,""Statistics"":null,""Orders"":null}'");
WHERE j.""Customer"" = '{""Name"":""Test customer"",""Age"":80,""ID"":""00000000-0000-0000-0000-000000000000"",""is_vip"":false,""Statistics"":null,""Orders"":null}'");
}

[Fact]
Expand Down Expand Up @@ -163,7 +164,7 @@ public void Bool_output()
AssertSql(
@"SELECT j.""Id"", j.""Customer"", j.""ToplevelArray""
FROM ""JsonbEntities"" AS j
WHERE CAST(j.""Customer""->>'IsVip' AS boolean)
WHERE CAST(j.""Customer""->>'is_vip' AS boolean)
LIMIT 2");
}

Expand Down Expand Up @@ -639,6 +640,7 @@ public class Customer
public string Name { get; set; }
public int Age { get; set; }
public Guid ID { get; set; }
[JsonPropertyName("is_vip")]
public bool IsVip { get; set; }
public Statistics Statistics { get; set; }
public Order[] Orders { get; set; }
Expand Down

0 comments on commit 25c83d5

Please sign in to comment.