Bata
Bata

Reputation: 313

Store string as jsonb column with npgsql

I have the following model

public class Guardian
    {
        public int id { get; set; }
        public string username { get; set; }
        public string email { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string gender { get; set ;}
        public string address { get; set; }

        public string Questions;

        public IList<Urgency> Urgencies { get; set; } = new List<Urgency>();
    }

And this line of code on my AppDbContext: DbContext

builder.Entity<Guardian>().Property(d => d.Questions).HasColumnType(NpgsqlDbType.Jsonb);

I want the Questions string field to be stored as JsonB type on the postgreSQL database. I get this error:

Argument 2: cannot convert from 'NpgsqlTypes.NpgsqlDbType' to 'string'

Which totally makes sense, but don't know how should i approach it, i have done research but nothing seems to target my particular situation. I'd truly appreciate some advice.

Upvotes: 0

Views: 1876

Answers (2)

Nit_16
Nit_16

Reputation: 41

This can be done by using DataAnnotation:

[Column(TypeName = "jsonb")]
public string Questions { get; set; }

Upvotes: 1

Shay Rojansky
Shay Rojansky

Reputation: 16692

HasColumnType - which is a general EF Core method - accepts a database type name is a string (e.g. the string jsonb), and not the Npgsql-specific NpgsqlDbType.Enum. You should simply change your code as follows:

builder.Entity<Guardian>().Property(d => d.Questions).HasColumnType("jsonb");

See the Npgsql EF Core provider docs for this and other info on JSON mapping.

Upvotes: 2

Related Questions