I am using Entity Framework Core with npgsql postgresql for Entity Framework Core.
My question is, using migrations, how do I mark a class property to generate a JSONB column type?
For example:
public class MyTableClass { public int Id { get; set; } // My JSONB column public string Data { get; set; } }
Thanks in advance.
The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering. JSONB supports GIN indexes.
In general, most applications should prefer to store JSON data as jsonb , unless there are quite specialized needs, such as legacy assumptions about ordering of object keys. RFC 7159 specifies that JSON strings should be encoded in UTF8.
Json processes input faster than jsonb as there is no conversion involved in this. Jsonb converts the JSON data into the binary form so it has slightly slower input due to the binary conversion overhead. There is no change in the Schema design while working with JSON.
The cause of the error ERROR: column “metadata” is of type jsonb but expression is of type bytea Hint: You will need to rewrite or cast the expression. if you are executing a native SQL DML statement.
Based on H. Herzl comment:
My final solution was something like this:
public class MyTableClass { public int Id { get; set; } [Column(TypeName = "jsonb")] public string Data { get; set; } }
Migrations generated this:
Data = table.Column<string>(type: "jsonb", nullable: true),
When updated the database with migrations, the Data column was created correctly with jsonb type.
Thank you H. Herzl!
using string
as was suggested by @bruno.almeida is a nice solution but couldn't be queried.
additional approaches are to use:
JsonDocument
or JsonElement)JsonDocument
being my favorite since it could be queried, is flexible and fast to setup, e.g.:
public JsonDocument Customer { get; set; }
more details at: https://www.npgsql.org/efcore/mapping/json.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With