I have a class:
public class DriverShortInfoElement
{
......
public DateTime? VistracksDateAdded { get; set; }
}
and I want to fill it by data from DbContext. I want to fill VistracksDateAdded only some condition is true, otherwise leave as null:
I try such way:
var list = (from i in _db.Drivers
select new DriverShortInfoElement()
{
.....
VistracksDateAdded = (i.ProblemSyncToVistracksDriver != null) ? i.ProblemSyncToVistracksDriver.DateAdded : null
}).ToList();
but compilation error. How to do it this simple thing?
I guess DateAdded
is a DateTime
. If you use the conditional operator you either have to cast the null
to DateTime?
or use new Nullable<DateTime>()
because there is no implicit conversion possible between null
and DateTime
:
VistracksDateAdded = i.ProblemSyncToVistracksDriver != null
? i.ProblemSyncToVistracksDriver.DateAdded
: new Nullable<DateTime>()