Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Aflred Avatar asked Oct 26 '14 00:10

Aflred


People also ask

Can you set DateTime to null?

Is it possible to set datetime object to null in C#? DateTime is a Value Type like int, double etc. so there is no way to assigned a null value.

Can we assign null to DateTime in C#?

CSharp Online TrainingUsing the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.

Can DateTime be null in SQL?

Using a DateTime column in an SQL table is quite common. Using it in . Net has one limitation – DateTime cannot be null as it is a struct and not a class.


2 Answers

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.

like image 101
ta.speot.is Avatar answered Oct 24 '22 06:10

ta.speot.is


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.

like image 3
Sapan Ghafuri Avatar answered Oct 24 '22 07:10

Sapan Ghafuri