Linq to SQL - 按两列排序

时间:2012-08-15 12:38:59

标签: c# asp.net-mvc linq-to-sql

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

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

 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 

Error

2 个答案:

答案 0 :(得分:1)

尝试删除

中的强制转换(DateTime)
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

答案 1 :(得分:1)

使用

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

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