无法隐式转换类型System.Linq.IQueryable <system.datetime>&#39;到&#39; System.DateTime&#39;

时间:2017-12-21 06:29:54

标签: c# linq

我的模态

Public class Details{
    public DateTime Startdate { get; set; }
    public DateTime EndDate { get; set; }
}

控制器

Details.Startdate = db.Bill.Where(u => u.BillId == Maxbillid).Select(u => u.EndDate );
Details.EndDate = db.Bill.Where(u => u.BillId == Maxbillid).Select(u => u.EndDate );

错误

  

无法隐式转换类型System.Linq.IQueryable&#39;到&#39; System.DateTime&#39;&#34;

2 个答案:

答案 0 :(得分:7)

使用FirstOrDefault

  

FirstOrDefault可以返回null,此代码不会检查

Details.Startdate = db.Bill.FirstOrDefault(u => u.BillId == Maxbillid).Startdate;
Details.EndDate = db.Bill.FirstOrDefault(u => u.BillId == Maxbillid).EndDate;

更优雅的设计是

var bill = db.Bill.FirstOrDefault(u => u.BillId == Maxbillid);

if (bill != null)
{
    Details.Startdate = bill.StarDate;
    Details.EndDate = bill.EndDate;
}

或者您Project可以Details直接进入Linq

var details = db.Bill.Where(u => u.BillId == Maxbillid)
                    .Select(bill => new Details
                       {
                           Startdate = bill.StarDate,
                           EndDate = bill.EndDate
                       })
                    .FirstOrDefault();

来自Msdn的更多资源

Enumerable.FirstOrDefault Method (IEnumerable)

答案 1 :(得分:2)

您可以使用FirstOrDefault并检查可能的空值。另外,要注意两次点击数据库显然是不必要的;

//Just get the entity for one time
var bill = db.Bill.FirstOrDefault(u => u.BillId == Maxbillid);   
if (bill != null)
{
    Details.Startdate = bill.StarDate;
    Details.EndDate = bill.EndDate;
}