Alex
Alex

Reputation: 1160

How to setup in EF Core, with Fluent API the default value for is required globally?

I created my first initial migration with some tables and columns, but I saw a thing, all my fields are not null and to every field which I want nullable (almost all) I need to specify the IsRequired(false)

enter image description here

There is a way to setup that all the fields to be nullable and only call the isRequired() (true) for those which I want to be required?

I don't want to use data annotations, or something else, only Fluent Api, so only if it exists a global setting for that in Fluent Api otherwise I will put to every field IsRequired. I want to decouple the models from FluentApi Config file because in the future if I want to use another ORM I only need to change FluentApi Config files.

Upvotes: 0

Views: 638

Answers (3)

granadaCoder
granadaCoder

Reputation: 27884

The answer to your question is "No".

You can add a class and static method to provide a single-source-of-truth constants.

public static class MyDefaultDictionary() {

   /* the below is false because ___________________ */
   public const bool IsRequiredDefault = false;

}

and

 .IsRequired(MyDefaultDictionary.IsRequiredDefault);

Upvotes: 0

izwaf yeb le assia
izwaf yeb le assia

Reputation: 37

when you setup your class you can work with nullable value types exemple :

public class a {

int? a { get; set; }

} 

Upvotes: 0

Ahmad Masoum
Ahmad Masoum

Reputation: 141

In your Entity you can set the properties to be nullable


Public class Booking 
{
        public Guid? MyProperty{ get; set; }

        public int? MyProperty{ get; set; }

        public decimal? MyProperty{ get; set; }
}

Or use JetBrains.Annotations

using JetBrains.Annotations;

Public class Booking 
{
        [CanBeNull]
        public Guid MyProperty{ get; set; }

        [CanBeNull]
        public int MyProperty{ get; set; }

        [CanBeNull]
        public decimal MyProperty{ get; set; }
}

Upvotes: 0

Related Questions