开发者

How to set Sql DateTime to null from LINQ

I have two cases when I would need to set DateTime field in Sql to null. I use C# and LINQ to SQL Classes. I read many questions on stackoverflow which are like my question but still I feed mine a bit different.

When we insert a new customer.

Corresponding code:

 Customer customer = new Customer();
 customer.CustomerName = txt_name.Text;
 customer.DOB = dtp_dob.Checked ? DateTime.Parse(dtp_dob.Value.ToString("yyyy-MM-dd")) : //send null here;

customer.DOB is System.DateTime.

What I tried is:

1)

 customer.DOB = dtp_dob.Checked ? DateTime.Parse(dtp_dob.Value.ToString("yyyy-MM-dd")) : SqlDateTime.Null;

But this will not succeed as SqlDateTime cann开发者_开发百科ot be converted to System.DateTime.

2)

    DateTime? nullDateTime = new DateTime();
 customer.DOB = dtp_dob.Checked ? DateTime.Parse(dtp_dob.Value.ToString("yyyy-MM-dd")) : nullDateTime.Value
 

In this case, build succeeds but it will throw an SqlDateTime overflow exception.

So then how to pass null value

Property of DOB Member in LINQ Dataclass

How to set Sql DateTime to null from LINQ

Many of them suggest to set Auto Generated Value to true and not to insert any value. True, it works in insert cases.

But now assume, there is already a customer entry where some datetime value is set to DOB field. Now user wants to clear this value (remove the birthdate), then in this case I have to pass a null value using UpdateOn to clear the datetime filed in corresponding customer row.

Thank you very much in advance :)


You should be able to use:

Customer customer = new Customer();
customer.CustomerName = txt_name.Text;
customer.DOB = dtp_dob.Checked 
                  ? DateTime.Parse(dtp_dob.Value.ToString("yyyy-MM-dd")) 
                  : (DateTime?) null;

Note the cast of null to DateTime?. The current problem is that the compiler can't work out the type of the conditional expression based on the operands.

The problem with your second attempt is that you're creating a new non-nullable DateTime value, i.e. 1st January 0001 AD. You could change that to:

DateTime? nullDateTime = null;
customer.DOB = dtp_dob.Checked 
                  ? DateTime.Parse(dtp_dob.Value.ToString("yyyy-MM-dd")) 
                  : nullDateTime;


plz try

if(dtp_dob.Checked )
{
   customer.DOB = DateTime.Parse(dtp_dob.Value.ToString("yyyy-MM-dd"));
}
else
{
   cstomer.DOB =null;
}

since DOB is nullable this code will give you what you want. BTW i can't find anything like nullDateTime.Value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜