实体框架中的左连接和case子句LINQ

时间:2014-05-28 23:53:07

标签: c# asp.net linq entity-framework

我需要进行左连接并使用select运算符大小写。 我的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     
        });

但是我必须添加一个新字段并且应该格式化,然后我的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()中添加ToList()或AsEnumerable(),则出现db.Agenda.ToList()db.Profissional.ToList()错误:

Object reference not set to an instance of an object.

如何使用案例和字段以及格式化字段进行左连接

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

试试这个:

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