how to insert null Datetime in database with entity framework codefirst

asp.net c# entity-framework

Question

my model includes a nullable datetime property.Im using CodeFirst

 public DateTime? GoDate { get; set; }

I would like to insert a nullvalue into that field but EF inserts the usual 00/00/0001 date instead of null, which also gives me an error.

im using microsoft sql server 2012.

DateTime? date = null;
var entity = new Model()
                {
                    GoDate = date
                };

DataContext.Models.Add(entity);
DataContext.SaveChanges();

give me the error.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated.

That is because sql server datetime cant have 00/00/0001, which EF automatically generates once it inserts a null datetime into the database.

I want to insert null into the db.

1
21
10/26/2014 12:51:48 AM

Popular Answer

EF inserts the usual 00/00/0001 date instead of null

There's nothing usual about it. Left to its own devices, EF 6.1 inserts NULL.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var DataContext = new StackOverflowContext();

            DateTime? date = null;
            var entity = new Model()
            {
                GoDate = date
            };

            DataContext.Models.Add(entity);
            DataContext.SaveChanges();
        }
    }

    class Model
    {
        public int ModelId { get; set; }

        public DateTime? GoDate { get; set; }
    }

    class StackOverflowContext : DbContext
    {
        public DbSet<Model> Models { get; set; }
    }
}

enter image description here

It's most likely your mappings or database schema are wrong.

15
10/26/2014 1:01:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow