Reputation: 1043
I have two columns, "date added" and "date modified".
I want to order all products by date modified, but since it can be null i want to get date added in that case.
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
};
This show me an error on
DateAdded = (DateTime) c.DateModified ?? c.DateAdded
Upvotes: 1
Views: 157
Reputation: 23646
try remove the cast (DateTime) in
DateAdded = (DateTime) c.DateModified ?? c.DateAdded
I've wrote snippet and in works fine
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};
Just to make sure:
Console.WriteLine (typeof(int) == res.ElementAt(0).Val.GetType()); //True
Console.WriteLine (typeof(int?) == res.ElementAt(0).Val.GetType()); //False
Upvotes: 1
Reputation: 4695
Use
DateAdded = c.DateModified.HasValue ? c.DateModified.Value : c.DateAdded
You're trying to assign nullable DateTime (c.DateModified) to a non-nullable DateTime field (DateAdded). You must take the value from nullable property if it exists or use another value (in your case c.DateAdded)
Upvotes: 1