0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

DBに1行だけのテーブルを作る

Posted at

設定値を1行だけ設置したい案件があったため備忘録として書きます
チェック制約でOneRowIdを1のみに制限する事で解消しました

CREATE TABLE public.settings (
    one_row_id integer NOT NULL,
    CONSTRAINT "CK_settings_one_row_id_Range" CHECK (one_row_id = 1)
);

ALTER TABLE ONLY public.settings 
    ADD CONSTRAINT pk_settings PRIMARY KEY (one_row_id);

ALTER TABLE public.settings ALTER COLUMN one_row_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME public.settings_one_row_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1
);

EF Coreを使っていれば以下のようにすると幸せになります

        [Key]
        [JsonIgnore]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Range(1, 1)]
        public int OneRowId { set; get; } = 1;

OneRowIdはFEに送りたくないのでJsonIgnoreします
DatabaseGenerated(DatabaseGeneratedOption.Identity)でDB側に生成してもらいます

良い良い方法があればコメントお願いします

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?