2016-05-14 48 views
0

我有這樣的SQL查詢:實體框架使用LINQ,INNER JOIN,GROUP BY排序方法的語法

SELECT 
    COUNT(PID.pid) AS Counted, 
    (SELECT TOP 1 Collect_id 
    FROM PID_Control 
    WHERE pid_controlY.org_pid = PID_Control.pid) as Collect_id 
FROM 
    PID 
INNER JOIN 
    PID_Control AS pid_controlY ON PID.pid = pid_controlY.pid 
GROUP BY 
    pid_controlY.Collect_id, pid_controlY.org_pid 

我想寫Linq中的一樣,但我不知道該如何處理本聲明:

,(select top 1 Collect_id from PID_Control where pid_controlY.org_pid = 
PID_Control.pid) as Collect_id 

我已經這樣做了,??? =錯線

var list = db.PID_Control 
      .Include(t => t.PID1) 
      .GroupBy(k => new { k.Collect_id }) 
      .Select(c => new Grouped 
       { 
        Collect_id = ??? 
        Counted = c.Select(q => q.PID1.pid1).Count(), 
       }) 
       .ToList(); 

如何在Linq中做到這一點?

public partial class PID_Control 
{ 
    public int pid_control_id { get; set; } 
    public Nullable<int> pid { get; set; } 
    public Nullable<int> Collect_id { get; set; }  
    public virtual PID PID1 { get; set; } 
} 


public partial class PID 
{ 
    public PID() 
    { 
     this.PID_Control = new HashSet<PID_Control>(); 
    } 
    public int pid1 { get; set; }  
    public virtual ICollection<PID_Control> PID_Control { get; set; } 
} 
+0

請添加兩個實體類和類的DbContext這裏也 –

+0

增加了他們現在 – user4144972

回答

0

我不知道你想什麼來實現的,而純粹是看數據這應該這樣做:

from pc in db.PID_Controls 
group pc by new { pc.Collect_id, pc.pid } into pcgrp 
select new Grouped 
{ 
    Collect_Id = pcgrp.SelectMany(pc => pc.PID.PID_Controls) 
         .Select(pc2 => pc2.Collect_id) 
         .FirstOrDefault(), 
    Counted = pcgrp.Count() 
} 

順便說一句,請你幫個忙,並使用集合的複數名稱(並遵守其他C#命名約定也不會損害)。

+0

它不工作,問題就在這裏:pid_controlY.org_pid = PID_Control.pid,不同的連接 但我現在didnt你可以混合linq在同一查詢中查詢語法和方法語法,感謝關於名稱的提示:) – user4144972

+0

「不同連接」是什麼意思?哪個字段與「PID」和「PID_Control」連接? –

+0

By PID pid_controlY.pid = PID_Control.pid – user4144972