实体框架中的左连接和大小写子句LINQ

本文关键字:大小写 子句 LINQ 连接 框架 实体 | 更新日期: 2023-09-27 18:05:51

我需要做一个左连接,也使用选择操作符的情况。我的LINQ basic是这样的:

resultado.Dados =
    (
        from a in db.AgendaHorario
        join b in db.Agenda on a.AgendaID equals b.AgendaID
        join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
        from e in d.DefaultIfEmpty()                        
        select new
        {
            id = a.AgendaHorarioID,
            Medico = e.Identificacao     
        });

但是我必须添加一个新的字段,它应该被格式化,然后我的LINQ看起来像这样:

resultado.Dados =
  (
    from a in db.AgendaHorario
    join b in db.Agenda on a.AgendaID equals b.AgendaID
    join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
    from e in d.DefaultIfEmpty()                        
    select new
    {
        id = a.AgendaHorarioID,
        Medico = e.Identificacao,
        start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")            
    }
  );

这个错误发生:

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

如果在db.AgendaHorario.ToList(), db.Agenda.ToList()db.Profissional.ToList()中添加ToList()或AsEnumerable(),出现的错误是:

Object reference not set to an instance of an object.

我应该怎么做,有一个左连接与大小写和字段和格式化字段

实体框架中的左连接和大小写子句LINQ

试试这个:

resultado.Dados =
(
    from a in db.AgendaHorario
    join b in db.Agenda on a.AgendaID equals b.AgendaID
    join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
    from e in d.DefaultIfEmpty()                        
    select new
    {
        id = a.AgendaHorarioID,
        Medico = e.Identificacao,
        start = a.Horario
    }).AsEnumerable().Select(x => new
    {
        id = x.id,
        Medico = x.Medico,
        start = x.start.ToString("yyyy-MM-dd HH:mm:ss")            
    }
);

尝试在变量中设置字符串,然后将其分配给您的查询,如下所示:

var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");
resultado.Dados =   (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()                        
select new
{
    id = a.AgendaHorarioID,
    Medico = e.Identificacao,
    start = myValue             
}   );