2

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!

4

2 回答 2

2

如果你做一个小实验,你会完全理解发生了什么:

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

两个变量normalDate和中的内容nullableDate是相同的,但它们不同:ToString("date in certain format")功能需要一个Date类型作为输入;您发送的是 Date 类型的修改版本(差别不大,但也不相同)。CDate您正在做的是将修改后的 Date 版本转换为实际有效的 Date 类型,因此 ToString() 功能可以正常工作。

你在做正确的事吗?是的,就 CDate 可以处理“空值”(CDate(Nothing)不输出任何错误)而言:您正在使给定变量适应 ToString() 的期望。

注意:我已经检查了上面代码输出的确切错误,它有效地提供了“从字符串“dd/MM/yy”到类型“整数”的转换无效。”。因此,当打算将 ToString("date") 与 Nullable Date 一起使用时,您得到的错误是标准错误;不要太描述性错误,这是真的。

于 2013-07-29T08:36:06.810 回答
0

处理可为空的属性时,db 列映射到 System.Nullable(Of T) (请参阅文档)。所以在你的情况下,el.birthday应该已经映射到Nullable(Of DateTime). 这个类有两个属性来处理你遇到的情况,即.ValueDoc)和.HasValueDoc)。

实际类型特定值存储在.Value您的情况下,您需要执行以下操作:

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

或者您可以使用.HasValuewhich 返回布尔值来指示是否有值:

If el.birthday.HasValue Then
   .bday = el.birthday.toString("dd/MM/yy") 
End If
于 2019-03-21T06:23:27.697 回答