2017-09-04 111 views
0

我有這樣的SQL代碼:LINQ - 左加入,集團通過,點心,

select A.Recurso_Id, sum(case when B.cita_id is null then 0 else 1 end) as Total_Eventos, 
a.Recurso_Nombre, a.Recurso_Email,a.Recurso_Activo 
from Agenda_Recurso a left join Agenda_Cita B 
on A.Recurso_Id=B.Recurso_Id 
group by A.Recurso_Id,a.Recurso_Nombre, a.Recurso_Email,a.Recurso_Activo 

而且,我需要平移,到LINQ,其實我有這樣的代碼:

List<Select> _ListaSelect = (from R in _LstRecursos 
           join C in _LstCitas 
           on R.Id equals C.Recurso_Id 
           group R by new {C.Recurso_Id, R.Nombre} into total 
           select new Select() 
           { 
            Cantidad_Eventos = total.Sum(R=> R.Id), 
            Recurso_Nombre= total.Max(R=> R.Nombre), 
            Recurso_Email=total.Max(R=>R.Email), 
            Recurso_Activo=total.Max(R=>R.Activo), 
            Id_Recurso=total.Max(R=>R.Id) 
           }).ToList(); 

但是,這是行不通的。你可以幫我嗎?

+2

請解釋*如何*它不工作。 –

+0

LINQ'join'默認使用內部連接。您的SQL查詢使用左連接。這就是爲什麼你會得到不同的結果。你必須使用'join ... in ... on ... into x from ... in x.DefaultIfEmpty()'模式來獲得LINQ中的左外連接。 – MarcinJuraszek

+0

在這種情況下,我想添加來自Resource_Id的所有內容,知道有多少約會關聯了一個資源,但是它的作用是添加我擁有的所有數字Resource_Id – Broodwing009

回答

1

我覺得你的查詢可以更簡單,

試試這個

var citasbyRecurso = 
      from r in recs 
      join c in citas on r.RecursoID equals c.RecursoID into cleft 
      select new 
      { 
       RecursoID = r.RecursoID, 
       Name = r.Name, 
       Email = r.Email, 
       Count = cleft.Where(x=>x.RecursoID == 
       r.RecursoID).Count(), 
      }; 

這是完整surce代碼,所以你可以運行在一個控制檯應用程序此查詢

class Program 
{ 
    static void Main(string[] args) 
    { 
     var recs = new List<Recursos> { 
new Recursos { Name = "Alex", Email = "A", RecursoID= 1 }, 
new Recursos { Name = "Juan", Email = "B", RecursoID= 2 }, 
new Recursos { Name = "Peter", Email = "C", RecursoID= 3 }, 
new Recursos { Name = "Julios", Email = "D", RecursoID= 4 }, 
new Recursos { Name = "Dennis", Email = "E", RecursoID= 5 }, 
new Recursos { Name = "Jhon", Email = "F", RecursoID= 6 }, 
}; 
     var citas = new List<Citas> { 
new Citas { RecursoID= 1, CitaID = 1 }, 
new Citas { RecursoID= 1, CitaID = 2 }, 
new Citas { RecursoID= 2, CitaID = 3 }, 
}; 

     var citasbyRecurso = 
      from r in recs 
      join c in citas on r.RecursoID equals c.RecursoID into cleft 
      select new 
      { 
       RecursoID = r.RecursoID, 
       Name = r.Name, 
       Email = r.Email, 
       Count = cleft.Where(x=>x.RecursoID == r.RecursoID).Count(), 
      }; 

     foreach (var item in citasbyRecurso) 
     { 
      Console.WriteLine(string.Format("{0} {1} {2} {3}", item.RecursoID,item.Name,item.Email, item.Count)); 
     } 
     Console.ReadLine(); 
    } 
} 

class Recursos 
{ 
    public int RecursoID; 
    public string Name; 
    public string Email; 
} 

class Citas 
{ 
    public int RecursoID; 
    public int CitaID; 
} 
+0

非常感謝您的幫助,這是我需要什麼,謝謝你,真的有效.... – Broodwing009