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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With