简体   繁体   English

将Datetime转换为字符串实体框架

[英]Convert Datetime to string entity framework

I Have the following Method: 我有以下方法:

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>();
}

But it's firing the following error when I try to convert a DateTime to String: 但是,当我尝试将DateTime转换为String时,它引发了以下错误:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression. LINQ to Entities无法识别方法'System.String ToString()',并且该方法无法转换为商店表达式。

I hope you can help me guys, I need that value as string, I can't change that to datetime. 希望您能对我有所帮助,我需要将该值作为字符串,不能将其更改为日期时间。

Entity Framework does not know how to execute ToString() method in SQL. 实体框架不知道如何在SQL中执行ToString()方法。 So you should load the data by using ToList() and then translate into SelectListItem as: 因此,您应该使用ToList()加载数据,然后将其转换为SelectListItem

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,
   ...
});

Remember that entity framework is converting your linq query to SQL. 请记住,实体框架将linq查询转换为SQL。 The error message is quite clear, it doesn't recognize the .ToString() method. 错误消息很清楚,它无法识别.ToString()方法。

You will have to retrieve the results using entity framework and then perform the needed DateTime to String conversions. 您将必须使用实体框架检索结果,然后执行所需的DateTime到String的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM