Search code examples
.netentity-framework-6code-first

How to force allow null in a Code First property?


I have a datetime property in a entity class that I want to migrate to sql server database.

I'm not assining it when creating the instance in the code, which means it is using mindate

Everything works great but it is saving in the column in the database structure as not nullable

I want to force it to be nullable, but so far I came up only with the oposite, using [Required]

any suggestions?

thanks


Solution

  • A property can't take [Required] tag and be nullable at the same time.

    To make DateTime types to make NULLs in the database, first get rid of [Required] tag then change your model to something like this:

    public System.Nullable<DateTime> Date { get; set; }
    

    OR

    public DateTime? Date { get; set; } 
    

    both will work.