2016-07-22 98 views
2

我有一個LINQ到SQL,並一直在研究如何使用LINQ到SQL來分組您的結果。我只看到有數量和總和的樣本。我的模型是,每個客戶訂單都有各種票據,可以有多個票據。現在它列出了所有的客戶訂單,並且如果它有多個票據,則會多次列出。Linq to Sql Group By without count

我如何通過LINQ到沒有資金SQL中使用組/計數總

我曾嘗試:

public IQueryable<object> getAllamcase() 
    { 
     try 
     { 
      var q = (from c in _context.Customer 
        join am in _context.table2 on c.id equals am.id 
        join ampn in _context.table3 on am.id equals ampn.id 
        join ay in _context.tabl4 on am.id equals ay.id 
        join oim in _context.table5 on am.id equals oim.id 
        group c.FileNum by new 
        { 
         FileNum = c.order, 
         assignmentdt = am.Assignment_DT, 
         oimname = oim.FullName, 
         notes = ampn.ProgressNotes, 
         years = ay.AMYear 
        }).AsQueryable(); 

      return q; 
     } 
     catch (Exception ex) 
     { 
      _logger.LogError("Could not get......", ex); 
      return null; 
     } 
    } 

我的結果看起來多jsons

Customer notes 
1    notes 1 
1    notes 2 
1    notes 3 
2    notes 1 
2    notes 2 

我只想讓它在一個json中返回,就像

Customer notes 
1    notes 1 
       notes 2 
       notes 3 

2    notes 1 
       notes 2 
+0

目前尚不清楚你想要做什麼。如果你不需要'.Count'屬性,就不要使用它。澄清你得到的輸出和你想要的東西。 –

+0

@JamesCurran,我已經更新了我想要的結果。 – epv

+1

您顯然還沒有發現導航屬性。像'Customer.Orders','Order.Notes'。他們給你你想要的東西。順便說一句,我希望這些不是你真正的表名。 –

回答

1

你的問題還不清楚,但正如我@GertArnold所說,如果你想加載客戶筆記,你應該使用導航屬性。另請參閱naming conventions。如果您正確地命名變量等,您的代碼將會更清晰。但根據你的問題標題,我可以建議你跟隨。試想一下,你有類:

public class Note 
{ 
    public int CustomerId { get; set; } 
    public string NoteName { get; set; } 
} 

而且你必須注意的名單如下:

List<Note> notes = new List<Note> 
{ 
    new Note { CustomerId = 1, NoteName = "note 1" }, 
    new Note { CustomerId = 1, NoteName = "note 2" }, 
    new Note { CustomerId = 1, NoteName = "note 3" }, 
    new Note { CustomerId = 1, NoteName = "note 4" }, 
    new Note { CustomerId = 2, NoteName = "note 1" }, 
    new Note { CustomerId = 2, NoteName = "note 2" }, 
    new Note { CustomerId = 3, NoteName = "note 1" }, 
}; 

如果你想從這個列表中可以easyli實現獲得客戶ID-S和相關附註它通過將它們分組:

var result = notes 
    .GroupBy(m => m.CustomerId) 
    .Select(g => new 
    { 
     CustomerId = g.Key, 
     Notes = g.Select(m => m.NoteName).ToList() 
    }); 

結果將是:

CustomerId || NoteName 
1    note 1 
       note 2 
       note 3 
       note 4 
2    note 1 
       note 2 
3    note 1 

我希望它能幫助你。