C# 为什么当我插入 DateTime null 时,SQL Server 中有“0001-01-01”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16692647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why when I insert a DateTime null I have "0001-01-01" in SQL Server?
提问by Alex
I try to insert the value null (DateTime) in my database for a field typed 'date' but I always get a '0001-01-01'. I don't understand, this field "allow nulls" and I don't know why I have this default value.
我尝试在我的数据库中为键入 'date' 的字段插入值 null (DateTime) 但我总是得到一个'0001-01-01'。我不明白,这个字段“允许空值”,我不知道为什么我有这个默认值。
I'm using C# asp .net with MVC (Entity Framework), this is my code :
我将 C# asp .net 与 MVC(实体框架)一起使用,这是我的代码:
Budget_Synthesis newBS = new Budget_Synthesis
{
Budget_Code = newBudgetCode,
Last_Modified_Date = null
};
db.Budget_Synthesis.AddObject(newBS);
Last_Modified_Date is typed System.DateTime? so I don't know why they change this 'null'.
Last_Modified_Date 的类型是 System.DateTime?所以我不知道他们为什么要改变这个“空”。
If I try to display the value on my application I get 01/01/0001 00:00:00
如果我尝试在我的应用程序上显示该值,我会得到 01/01/0001 00:00:00
And 0001-01-01with SSMS
和0001-01-01SSMS
Someone can explain me why I can't get a real 'NULL' ?
有人可以解释我为什么我不能得到一个真正的 'NULL' 吗?
Best regards
此致
采纳答案by Hugo Pedrosa
I think this is the value corresponding to the null
我认为这是与空值对应的值
回答by Nikola Dimitroff
When saying you are trying to put a null DateTime, are you using a Nullable<DateTime>(a.k.a DateTime?) or simply DateTime? The latter is a value type and its default value is precisely 01/01/0001 00:00:00
当你说你试图放置一个 null 时DateTime,你是使用Nullable<DateTime>(又名DateTime?)还是简单的DateTime?后者是一个值类型,它的默认值正好是01/01/0001 00:00:00
回答by Spaceman
If Last_Modified_Dateis of type DateTime, you can't have "real null" because DateTime structure- as others already said- is not nullable. So your sample code will not even compile.
如果Last_Modified_Date是 type DateTime,你不能有“真正的空”,因为DateTime 结构- 正如其他人已经说过的 - 不可为空。所以你的示例代码甚至不会编译。
If Last_Modified_Dateis of type DateTime?(Nullable<DateTime>) your code is correct, but -as @Nikola Dimitroff said in his answer- you can't have "real null" in your database because the default value for DateTime?is 01/01/0001 00:00:00.
如果Last_Modified_Date是DateTime?( Nullable<DateTime>)类型,您的代码是正确的,但是 - 正如@Nikola Dimitroff 在他的回答中所说 - 您的数据库中不能有“真正的空”,因为默认值为DateTime?01/01/0001 00:00:00 .
The "real null" you are looking for is DBNull.Value, but you can use it only for System.DBNulltype; if you assign Last_Modified_Date = DBNull.Value, whatever the type of Last_Modified_Dateis, your code will not compile.
您正在寻找的“真正的空”是DBNull.Value,但您只能将它用于System.DBNull类型;如果你赋值Last_Modified_Date = DBNull.Value,无论Last_Modified_Date是什么类型,你的代码都不会编译。

![C# WebAPI POST [FromBody] 未绑定](/res/img/loading.gif)