简体   繁体   English

在 Entity Framework Core 中为 PostgreSQL 表的计算列设置公式

[英]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我有一个带有 Id 和 json 属性的简单模型和一个计算列,它是 json 列中'tile'键的值

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:在配置中,我设置了计算Title值的方式:

    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.问题出在title如何转义的"(\\"JsonInfo\\"->>''title'')"中。 How can i fix it?我该如何解决?

Just to mention, i use latest version of PostgreSQL顺便提一下,我使用最新版本的 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.您提供给 HasComputedColumnSql 的 SQL 不是文本文字,而是实际的 SQL。 So the following should work:所以以下应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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