1

我有两列,“添加日期”和“修改日期”。

我想按修改日期订购所有产品,但由于它可以为空,我想在这种情况下添加日期。

 var q = from c in db.Products
                where c.UserID == UserID
                orderby c.DateModified ?? c.DateAdded descending
                select
                    new ManageProducts
                        {
                            ID = c.ID,
                            Image = c.Photo.PhotoFile,
                            Name = c.Name,
                            DateAdded = (DateTime) c.DateModified ?? c.DateAdded 
};

这告诉我一个错误

DateAdded = (DateTime) c.DateModified ?? c.DateAdded 

错误

4

2 回答 2

1

利用

DateAdded = c.DateModified.HasValue ? c.DateModified.Value : c.DateAdded

您正在尝试将可为空的 DateTime (c.DateModified) 分配给不可为空的 DateTime 字段 (DateAdded)。如果它存在,则必须从可为空的属性中获取值或使用另一个值(在您的情况下为 c.DateAdded)

于 2012-08-15T13:01:28.443 回答
1

尝试删除演员表(日期时间)

DateAdded = (DateTime) c.DateModified ?? c.DateAdded 

我已经写了片段并且工作正常

var sample = new [] {new {Nul = (int?) 5,    Val = 6}, 
                     new {Nul = (int?) null, Val = 6}};

var res = from value in sample 
          orderby value.Nul ?? value.Val
          select new {Val = value.Nul ?? value.Val};

只想确认一下:

Console.WriteLine (typeof(int) == res.ElementAt(0).Val.GetType()); //True
Console.WriteLine (typeof(int?) == res.ElementAt(0).Val.GetType()); //False
于 2012-08-15T12:56:01.573 回答