how to insert null Datetime in database with entity framework codefirst

asp.net c# entity-framework

Question

A datetime attribute that is nullable is part of my model. I employ CodeFirst

 public DateTime? GoDate { get; set; }

I wanted to insert a nullvalue into that field, but EF instead inserted the customary 00/00/0001 date, which also caused me to receive an error.

I'm using SQL Server 2012 from Microsoft.

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

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

send me the mistake.

An out-of-range value was produced by converting a datetime2 data type to a datetime data type. The statement has come to an end.

This is due to the fact that sql server datetime cannot contain 00/00/0001, which EF creates by default after inserting a null datetime into the database.

I want to add null to the database.

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

Popular Answer

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

There's usual nothing about it. EF 6.1 inserts when left to its own devices.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

Your database schema or mappings are probably incorrect.

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