简介
我正在使用PostreSQL JSON support,它为我提供了强大的API,但其中包含一些奇怪的字符。
EF处理了其中的一些(例如->>
),但其他处理了问题(例如@>
)
目标:
在.net核心EF中将以下查询作为原始查询执行:
SELECT * FROM todoitem WHERE "JsonPayload" @> '{"ListProp": [{"Name": "listProp1Name", "Value": "listProp1Value"}]}'
当前情况
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();
注意:这里的字符串分隔请不要怪我。我只是在缩小问题范围。输出字符串与我在数据库中执行的字符串完全相同(在该字符串中起作用)。
问题
似乎@
字符受到了指责,因为它被解释为命名参数。
所以问题是-如何逃脱它?
也有可能,方括号({
和}
)也有问题,因为它们也用作变量指示符。如果您知道如何逃脱它们,也请写信。
很明显,我尝试过四处搜寻,但似乎逃避@
符号并不常见。
堆栈跟踪:
在两种情况下都是相同的-使用@>
和@@>
时。
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()
答案 0 :(得分:1)
也许这不是确切答案,但是您可以使用dapper
使用dapper,您可以编写以下内容:
var connection = new NpgsqlConnection(_configuration.GetConnectionString("DefaultConnection"));
var items = connection
.Query<TodoItem>(
@"SELECT * FROM todoitem WHERE ""JsonPayload"" @> '{""ListProp"": [{""Name"": ""listProp1Name"", ""Value"": ""listProp1Value""}]}'")
.ToList();
答案 1 :(得分:0)
基于How to: Directly Execute SQL Queries | Microsoft Docs和@ - C# Reference | Microsoft Docs
var sql=@"SELECT * FROM todoitem WHERE ""JsonPayload"" @> '{""ListProp"": [{""Name"": ""listProp1Name"", ""Value"": ""listProp1Value""}]}'";
var items = _context.Database.SqlQuery<TodoItems>(sql).ToList();