简体   繁体   中英

PostgreSQL JSONB serialization/de-serialization with Entity Framework Core 6 and .NET Core 6

I am exploring Microsoft Entity Framework Core 6.0.3 with the .NET 6 framework.

My target database is PostgreSQL - and I'm using Npgsql.EntityFrameworkCore.PostgreSQL (6.0.3).

I have two classes

public class ExtendedData
{
      public List<string> familyMembers { get; set; }
      public List<string> phoneNumbers { get; set; }
}

public class Employee
{ 
      public String Id { get; set; }
      public String Name { get; set; }
      public List<ExtendedData> Data { get; set; }
}

I wrote following code to retrieve data from the Employee table:

List<Employee> list = db.Employees.Where(x => x.Id == "1234").ToList();

I able to see list[0].Id , list[0].Name populated as expected. I also able to see list[0].Data[0] available.

Problem is I am NOT able to see list[0].Data[0].familyMembers and list[0].Data[0].phoneNumbers .

Problem is, in PostgreSQL database, familyMembers column is actually Family Members and phoneNumbers is Phone Numbers .

Data column of Employee table is set to jsonb column and has the following data:

[
    { 
      "Family Members": ["Mother", "Father", "Wife"], 
      "Phone Numbers": ["9998887765", "1123444444"]
    }
]

My question is: how do I map Family Members property of the jsonb column into familyMembers array of my C# class?

With my investigation, if I use familyMembers property in JSON in database, it works

[
    {
        "familyMembers": ["Mother", "Father", "Wife"], 
        "phoneNumbers": ["9998887765", "1123444444"]
    }
]

Using JsonProperty("Family Members") attribute however didn't work.

public class ExtendedData
{ 
      JsonProperty("Family Members") 
      public List<string> familyMembers { get; set; }
...
}

Not that - even if it doesn't make sense in this example, Data property has to be collection (List type) and familyMembers and phoneNumbers is a list of strings.

Thanks, Atul

I got hint from https://www.npgsql.org/efcore/mapping/json.html?tabs=fluent-api%2Cpoco

I was focusing on JsonProperty but looks like another attribute JsonPropertyName worked.

public class ExtendedData
{
[System.Text.Json.Serialization.JsonPropertyName("Family Members")]
      public List<string> familyMembers { get; set; }

[System.Text.Json.Serialization.JsonPropertyName("Phone Numbers")]
      public List<string> phoneNumbers { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM