[英]how to insert null Datetime in database with entity framework codefirst
my model includes a nullable datetime property. 我的模型包含一个可以为空的datetime属性。 Im using CodeFirst
我正在使用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. 我想在该字段中插入一个nullvalue但是EF插入通常的00/00/0001日期而不是null,这也给了我一个错误。
im using microsoft sql server 2012. 即时通讯使用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. 将datetime2数据类型转换为日期时间数据类型会导致超出范围的值。\\ r \\ n语句已终止。
That is because sql server datetime cant have 00/00/0001, which EF automatically generates once it inserts a null datetime into the database. 这是因为sql server datetime不能有00/00/0001,一旦它将null日期时间插入数据库,EF就会自动生成。
I want to insert null into the db. 我想在db中插入null。
EF inserts the usual 00/00/0001 date instead of null
EF插入通常的00/00/0001日期而不是null
There's nothing usual about it. 它没什么常见的 。 Left to its own devices, EF 6.1 inserts
NULL
. 保留给自己的设备,EF 6.1插入
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.
然后从您的控制器发送null将正常工作。
[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
在DateTime日期之前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.