Dev*_*ter 1 linq asp.net-mvc nullable
如何检查Linq中的Null?
我有一个第三方代码,它返回一个可以为空DataTable的列类型DateTime.
我的代码:
var profile = (from d in ds.Tables[0].AsEnumerable()
select new User
{
FirstName = d["FirstName"].ToString(),
Birthdate = Convert.ToDateTime(d["BirthDate"].ToString())
}).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
返回一个错误是,Object cannot be cast from DBNull to other types在Birthdate=声明.
我尝试使用以下代码但返回一个强制转换异常(无法从字符串强制转换为DateTime?)
Birthdate = (DateTime?)d["BirthDate"].ToString();
Run Code Online (Sandbox Code Playgroud)
有没有办法快速检查空值?
我没有测试过这个,但您可以尝试以下方法:
Birthdate = d.Field<DateTime?>("BirthDate")
Run Code Online (Sandbox Code Playgroud)
来自MSDN:
Field方法支持将列作为可空类型进行访问.如果DataSet中的基础值是[DBNull.] Value,则返回的可空类型的值将为null.