.NET core Entity Framework - escaping "@" character

Viewed 1770

Intro
I'm using the PostreSQL JSON support which gives me a powerful API, but it contains some weird characters.
EF handles some of them (for example ->>), but has problems with others (for example @>)

Goal:
Execute the following query as a raw query in the .net core EF:

SELECT * FROM todoitem WHERE "JsonPayload" @> '{"ListProp": [{"Name": "listProp1Name", "Value": "listProp1Value"}]}'

Current situation

string select = "SELECT * FROM todoitem";
string where = "WHERE \"JsonPayload\" @>";
string listQuery = "'{\"ListProp\": [{\"Name\": \"listProp1Name\", \"Value\": \"listProp1Value\"}]}'";

string query = $"{select} {where} {listQuery}";
Console.WriteLine(query);

var items = _context.TodoItems.FromSql(query).ToList();

Note: Please do not blame me for the string separation here. I was just narrowing down the problem. The output string is exactly the same as the one that I execute in the database (where it works).

The problem
Looks like the @ character takes the blame, because it's being interpreted as a named parameter.
So the question is - how to escape it?

it is also possible, that brackets ({ and }) are also going to be problematic, as they are used as variable indicators too. Please also write if you know how to escape them.

Obviously I tried googling around, but it seems it's not common to escape the @ sign.

Stack Trace: it's the same in both cases - when using @> and @@>.

fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred in the database while iterating the results of a query for context type 'dotnet_postgres_test.Models.TodoContext'.
      System.FormatException: Input string was not in a correct format.
         at System.Text.StringBuilder.FormatError()

2 Answers

maybe that's not an exact answer, but you can use dapper

with dapper you can just write the following:

var connection = new NpgsqlConnection(_configuration.GetConnectionString("DefaultConnection"));

var items = connection
    .Query<TodoItem>(
        @"SELECT * FROM todoitem WHERE ""JsonPayload"" @> '{""ListProp"": [{""Name"": ""listProp1Name"", ""Value"": ""listProp1Value""}]}'")
    .ToList();
Related