无法使用LINQ to SQL将空值加载到DateTime属性

时间:2016-04-20 12:23:16

标签: c# linq linq-to-sql

我从数据库中获取数据并将其用作Repeater的数据源有时我的日期值为null。

var mQuery = (from rmm in db.global_rawmaterial_mains
              where //bla bla bla 
              orderby rmm.name
              select new
              {
                  rmm.name, 
                  rmm.source,
                  date = rmm.global_rawmaterial_entries
                            .Where(p => p.date <= selectedDate)
                            .OrderByDescending(p => p.date)
                            .Select(p => (DateTime?)p.date) // here this date I want to convert .ToString("dd-MM-yyyy")
              });

我看到的日期如下:2/9/2009 12:00:00 AM。在上面的查询中,如何将其转换为.ToString();因为我无法将其用作:

.Select(p => (DateTime?)p.date.ToString("dd-MM-yyyy")) //Cannot cast expression of type string to DateTime  

我无法使用:

 .Select(p => (string?)p.date.ToString())// Only non-nullable value type could be underlying of 'System.Nullable'

如果我尝试:

.Select(p =>p.date.ToString())

我收到错误:

Exception: The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type.

1 个答案:

答案 0 :(得分:0)

date = rmm.global_rawmaterial_entries
                            .Where(p => p.date <= selectedDate)
                            .OrderByDescending(p => p.date)
                            .Select(p => p.date)
.Select(d=>d.ToString());