YingLi Zhuang
YingLi Zhuang

Reputation: 35

LINQ - How to insert null DateTime into database column?

Using LINQ, how do I insert a null value into a SQL Server 2008 DateTime column?

The code below inserts "1/1/1900 12:00:00 AM", But I want to insert "NULL" instead

CreatDate = System.Data.SqlTypes.SqlDateTime.Null

Upvotes: 3

Views: 7355

Answers (2)

Jason.Net
Jason.Net

Reputation: 401

Ensure that the column in the DB is set to allow NULL and your entity property, "CreateDate" is defined as "DateTime? CreateDate {get;set;}". Then, simply set "CreateDate = null".

Upvotes: 6

mattmc3
mattmc3

Reputation: 18335

Your CreateDate property needs to be declared Nullable<DateTime> (aka DateTime?). Then, you can set that property on your Linqed-up object to null (not System.Data.SqlTypes.SqlDateTime.Null, just plain old C# null) and you should get the desired result. This of course assumes that your SQL table has the column properly defined to allow NULLs and that your definition for the column in the DBML also allows them.

Upvotes: 0

Related Questions