关于c#:将Datetime转换为字符串实体框架

Convert Datetime to string entity framework

我有以下方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public List<REP_MEDIDORDISPLAY> GetAllMedidoresDisplay()
{          
    return ent.TB_MEDIDOR.Select(x => new REP_MEDIDORDISPLAY
    {
            Data_TOI = x.Data_TOI,
            Elemento = x.Elemento,
            Fase = x.Fase,
            KdKe = x.KD_KE,
            N_Equipamento = x.Numero,
            Tensao = x.Tensao,
            Status =  x.TB_REVISAO.Count > 0 ?"Revis?£o":
                      x.TB_CHECAGEM_INTERNA.Count > 0 ?"Checagem interna":
                      x.TB_MESACALIBRACAO.Count > 0 ?"Mesa de calibra?§?£o":
                      x.TB_HIPOT.Count > 0 ?"Hipot":
                      x.TB_INSPECAO.Count > 0?"Inspe?§?£o" :
                      x.TB_AGENDAMENTO.FirstOrDefault(y => y.ID_Medidor == x.ID).Data_Agendamento.HasValue ?
                  --> Error here (x.TB_AGENDAMENTO.FirstOrDefault(y => y.ID_Medidor == x.ID).Data_Agendamento.Value.ToString()) :String.Empty
    }).ToList<REP_MEDIDORDISPLAY>();
}

但是当我尝试将DateTime转换为String时,它会引发以下错误:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

希望您能帮到我,我需要将该值作为字符串,不能将其更改为datetime。


实体框架不知道如何在SQL中执行ToString()方法。因此,您应该使用ToList()加载数据,然后将其转换为SelectListItem as:

1
2
3
4
5
6
7
8
9
10
11
12
return ent.TB_MEDIDOR.ToList().Select(x => new SelectListItem
{
    Data_TOI = x.Data_TOI,
    ...
    // can convert DateTime to String here
})
// Then you can select this as a REP_MEDIDORDISPLAY if you want
.Select(y => new REP_MEDIDORDISPLAY
{
   Data_TOI = y.x.Data_TOI,
   ...
});


请记住,实体框架正在将您的linq查询转换为SQL。错误消息非常清楚,无法识别.ToString()方法。

您将必须使用实体框架检索结果,然后执行所需的DateTime到String的转换。