简体   繁体   中英

how to insert null Datetime in database with entity framework codefirst

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.

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; }
    }
}

在此输入图像描述

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

Or you can just set like this:

var entity= new Model
{
    GoDate = (DateTime?) null
}
DataContext.Models.Add(entity);
DataContext.SaveChanges();

I think it is a little bit cleaner.

You Can use this :

 Nullable<DateTime> date=null;
 var entity = new Model()
            {
                GoDate = date
            };

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

You can use something like this in your model. then sending null from your controller will work fine.

 [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [Display(Name = "Date")]
        public DateTime? Date { get; set; }

Notice the "?" before the DateTime Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM