简体   繁体   中英

Set formula for Computed column of PostgreSQL table in Entity Framework Core

I have a simple model with Id and a json property and a computed column which is value of 'tile' key in the json column

public class Book 
{
    public int Id { get; set; }

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

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string Title { get; set; }
}

in the configuration I set the way which the value of Title is caculated:

    builder.Property(t => t.Title).HasComputedColumnSql("(\"JsonInfo\"->>''title'')", stored:true).HasColumnType("varchar(150)");

the migration is build without problem, but unfortunately the database update ends with an error:

42601: syntax error at or near "title"

The problem is within the "(\\"JsonInfo\\"->>''title'')" that how the title is escaped. How can i fix it?

Just to mention, i use latest version of PostgreSQL

You shouldn't be escaping the title with twice single-quotes; the SQL you give to HasComputedColumnSql isn't a text literal, it's actual SQL. So the following should work:

.HasComputedColumnSql("\"JsonInfo\"->>'title'", stored: true)

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