Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core jsonb column type

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.

like image 370
bruno.almeida Avatar asked Mar 29 '17 09:03

bruno.almeida


People also ask

What type is Jsonb?

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.

Should I use Jsonb or JSON?

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.

Is Jsonb faster than JSON?

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.

Is of type Jsonb but expression is of type?

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.


2 Answers

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!

like image 153
bruno.almeida Avatar answered Sep 29 '22 11:09

bruno.almeida


using string as was suggested by @bruno.almeida is a nice solution but couldn't be queried.

additional approaches are to use:

  • As System.Text.Json DOM types (JsonDocument or JsonElement)
  • As strongly-typed user-defined types (POCOs)

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

like image 35
Neil Avatar answered Sep 29 '22 10:09

Neil