skip to Main Content

So I’m transferring domain classes (a lot) to the postgres with EF6.
Classes can have value type properties, like int and float, and are being transferred to postgres as NOT NULL.

I can’t make my domain classes properties nullable, as it could break business logic.

I saw this approach – make props optional

but this means that I have to manually do this in OnModelCreating in my dbcontext for every class I Have, right?

So, is there any way to make value types (for all my domain classes) nullable in database, like, at initial migration (or any other way in bulk) – so I dont have to manually specify it in OnModelCreating for every class I have? Maybe it is possible with some custom convention for it?

tldr – I want to make evey value type property of every class nullable in database with ef6, without making it nullable in domain itself

Thanks!

2

Answers


  1. Did you try in your Domain classes ? Nullable value types

    public class Book
    {
        public int ID { get; set; }
        public double? Price { get; set; }
    }
    
    Login or Signup to reply.
  2. There is a DbModelBuilder.Properties() method.

    It can be used to set the necessary values for all properties in the OnModelCreating method.

    modelBuilder.Properties().Configure(p => p.IsOptional());
    

    However, this will change all properties. Of course, there is no need to change the primary keys and some other columns. Therefore, they need to be filtered out.

    modelBuilder.Properties().Where(p => p.Name != "Id").Configure(p => p.IsOptional());
    

    Or something like that:

    modelBuilder.Properties().Where(p => p.Name.EndsWith("Id")).Configure(p => p.IsOptional());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search