Reputation: 46750
I have the following table definition
[Table("MyTable")]
public class MyTable: BaseEntity
{
[Required]
public string A{ get; set; }
[Required]
[Column(TypeName = "json")]
public string B{ get; set; }
}
Column B looks like this:
{"Data": [{"Id":"b8a3cbbc-a4d6-4697-8a0b-cb1d15be179d"}]} (aside from Id there are other properties but for brevity I removed them)
In Entity Framework I want to match all MyTable's where the Id in B is a certain value and A has a certain value. I have tried a lot of things and get numerous errors. How can I add to the following code to achieve what I want?
var results =
_repository.Get<MyTable>(_ => _.A == "Something" && _.B = ???);
Upvotes: 2
Views: 5187
Reputation: 1040
You can use "EF.Functions.JsonContains
" function, but the B
column needs to be "jsonb
" type instead of "json
".
[Required]
[Column(TypeName = "jsonb")]
public string B { get; set; }
Example:
var search = "[{\"Id\": \"b8a3cbbc-a4d6-4697-8a0b-cb1d15be179d\"}]";
var results = _context.MyTable2
.Where(_ => _.A == "Something"
&& EF.Functions.JsonContains(_.B, search));
Similar answer HERE
Also, you can type your query and use Dapper.
Example:
with temp AS(
select t."Id", t."A", json_array_elements(t."B"->'Data') as B1 from "MyTable" t
)
select * from temp t
where
t."A"='Something' and
t.b1->>'Id'='b9a3cbbc-a4d6-4697-8a0b-cb1d15be179a'
Upvotes: 4