我有一个班级:
public class DriverShortInfoElement
{
......
public DateTime? VistracksDateAdded { get; set; }
}
我希望用来自DbContext的数据来填充它。我想填充VistracksDateAdded只有一些条件为真,否则保留为null:
我试着这样:
var list = (from i in _db.Drivers
select new DriverShortInfoElement()
{
.....
VistracksDateAdded = (i.ProblemSyncToVistracksDriver != null) ? i.ProblemSyncToVistracksDriver.DateAdded : null
}).ToList();
但编译错误。怎么做这个简单的事情?
答案 0 :(得分:3)
我猜DateAdded
是DateTime
。如果您使用条件运算符,则必须将null
强制转换为DateTime?
或使用new Nullable<DateTime>()
,因为null
和DateTime
之间不存在隐式转换:
VistracksDateAdded = i.ProblemSyncToVistracksDriver != null
? i.ProblemSyncToVistracksDriver.DateAdded
: new Nullable<DateTime>()
答案 1 :(得分:3)
还有另一个运营商:Null conditional operator
VistracksDateAdded = i.ProblemSyncToVistracksDriver?.DateAdded
答案 2 :(得分:-1)
var query =
from driver in _db.Drivers
select new DriverShortInfoElement
{
VistracksDateAdded = driver.ProblemSyncToVistracksDriver != null
? driver.ProblemSyncToVistracksDriver.DateAdded
: default(DateTime?)
};