Entity Framework Core set nullable prop only if default is true

857 Views Asked by At

I use the database first approach and I use Postgres 14.

I have several boolean fields in the database, I set them all to non null and in some I set the default value.

I noticed that when I scaffold the database, only the fields where the default value is set to false, the property is generated in a non-nullable way. Fields where set to true are generated nullable

enter image description here

enter image description here

public partial class Sensor
{
    // ...
    public bool IsActiveLimits { get; set; }

    public bool? IsEnable { get; set; }
    // ...
}

How can I force the scaffold to also generate these fields not nullable?

PS: I can also remove the default value and create a before insert trigger and set the value in that case, but I would still like to use the default field

HOW TO REPLICATE THE ERROR

This is litle project to replicate the error.

I use terminal sql shell psql to create database, schema and table.

--
-- PostgreSQL database dump
--

CREATE DATABASE null_database WITH TEMPLATE = template0 ENCODING = 'UTF8';

ALTER DATABASE null_database OWNER TO postgres;

\connect null_database

CREATE SCHEMA database_schema;

ALTER SCHEMA database_schema OWNER TO postgres;

CREATE TABLE database_schema.table_bool (
    table_bool_id integer NOT NULL,
    default_true boolean DEFAULT true NOT NULL,
    default_false boolean DEFAULT false NOT NULL
);


ALTER TABLE database_schema.table_bool OWNER TO postgres;

CREATE SEQUENCE database_schema.table_bool_table_bool_id_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER TABLE database_schema.table_bool_table_bool_id_seq OWNER TO postgres;

done this, with VS2022 I create a console app, I install the following packages:

Install-Package Microsoft.Extensions.DependencyInjection

Install-Package Microsoft.EntityFrameworkCore.Tools

Install-Package Microsoft.EntityFrameworkCore.Design

Install-Package Microsoft.Extensions.Configuration

Install-Package Microsoft.Extensions.Configuration.FileExtensions

Install-Package Microsoft.Extensions.Configuration.Json

Install-Package Npgsql.EntityFrameworkCore.PostgreSQL

once the installation is complete, from the command line within the project I launch the following command:

dotnet ef dbcontext scaffold "Host=localhost;port=5433;Database=null_database;Username=postgres;Password=postgres" Npgsql.EntityFrameworkCore.PostgreSQL -o Models --no-pluralize

Version ef core: Entity Framework Core .NET Command-line Tools 7.0.0

Result

public partial class TableBool
{
    public int TableBoolId { get; set; }

    public bool? DefaultTrue { get; set; }

    public bool DefaultFalse { get; set; }
}
0

There are 0 best solutions below