Sto provando a prendere un valore DateTime e, se non è null, restituisce la stringa Short Time. La mia domanda è simile al seguente: (timein NON è NULLABLE, mentre TimeOut è NULLABLE)Perché non posso lanciare il valore DateTime nullable come stringa in una query LinQ?
var times = from t in db.TimePostings
where t.MemberID == member.MemberID
select new
{
Date = t.TimeIn.ToShortDateString(),
TimeIn = t.TimeIn.ToShortTimeString(),
TimeOut = t.TimeOut.HasValue ? t.TimeOut.Value.ToShortTimeString() : "-------"
};
gvTimePostings.DataSource = times;
gvTimePostings.DataBind();
, ma questo viene a mancare quando provo a DataBind con l'errore:
Could not translate expression 'Table(TimePosting).Where(t => (t.MemberID == Invoke(value(System.Func
1[System.String])))).Select(t => new <>f__AnonymousType8
4(Date = t.TimeIn.ToShortDateString(), TimeIn = t.TimeIn.ToShortTimeString(), TimeOut = IIF(t.TimeOut.HasValue, (t.TimeOut ?? Invoke(value(System.Func`1[System.DateTime]))).ToShortTimeString(), "-------"), Hours = ""))' into SQL and could not treat it as a local expression.
Inoltre ottengo un errore simile se cerco di usare:
TimeOut = t.TimeOut.HasValue ? Convert.ToDateTime(t.TimeOut).ToShortTimeString() : "-------"
tuttavia, se cambio la proprietà TimeOut a:
TimeOut = t.TimeOut.HasValue ? t.TimeOut.ToString() : "-------",
funziona correttamente, ma non formatta l'orario come lo desidero (shortTimeString).
cosa succede?
Suppongo che "AsEnumerable()" causi lo stesso effetto come "ToList()" nella risposta di Justin. L'uno o l'altro metodo è "migliore" da usare? –
@ matthew_360: Non proprio lo stesso effetto, no - 'ToList()' deve creare un elenco di tutti gli elementi, piuttosto che eseguirne il flusso. Va bene se userai 'times' in più posti senza qualcosa di buffering * che * risultasse, ma altrimenti non vedo alcun motivo per costruire il buffer - Personalmente userò' AsEnumerable', che serve * esclusivamente * allo scopo vuoi: conversione da 'IQueryable' a 'IEnumerable '. –