Entity Framework: nullable DateTime toString(format) in vb.net handling

Given a table Element with a DateTime field birthday (not null), in Entity framework 4 I am allowed to do:

Dim mylist = (From el in Element Select el).ToList()
     .Select(function(el) new with { 
           .bday = el.birthday.toString("dd/MM/yy") 
           }

I am now required to change birthday to be nullable, therefore I change the table in SQL server and then update my ModelDB in Visual studio. The result is that the line:

           .bday = el.birthday.toString("dd/MM/yy") 

raises an exception as "Invalid cast from integer to string "dd/mm/yy"). The only way to get it "fixed" is to change the line this way:

           .bday = CDate(el.birthday).toString("dd/MM/yy") 

Is this the correct approach? Now that I have a nullable Datetime, how to handle the case when el.birthday is null?

Thanks!


If you do a small experiment, you would understand perfectly what is happening:

Dim normalDate As Date = Now
Dim nullableDate As Nullable(Of Date) = normalDate

Dim normalToText As String = normalDate.ToString("dd/MM/yy") 'Works perfectly

Dim nullableToText As String = nullableDate.ToString("dd/MM/yy") 'Error

The content in both variables, normalDate and nullableDate , is identical but they are not: the ToString("date in certain format") functionality expects a Date type as input; what you are sending is a modified version of the Date type (not too different, but not the same either). With CDate what you are doing is converting the modified version of Date into an actually valid Date type and thus the ToString() functionality works without any problem.

Are you doing the right thing? Yes, as far as CDate can deal with "nulls" ( CDate(Nothing) does not output any error): you are adapting the given variable to what ToString() expects.

NOTE: I have checked the exact error output by the code above and it effectively delivers a "Conversion from string "dd/MM/yy" to type 'Integer' is not valid.". Thus the error you are getting is the standard error when intending to use ToString("date") with a Nullable Date; not too descriptive error, this is true.

链接地址: http://www.djcxy.com/p/42828.html

上一篇: 获取空引用异常,尝试将零推入堆栈

下一篇: 实体框架:在vb.net处理中可以为空的DateTime toString(格式)