2017-03-16 120 views
0

我需要在程序中實現一個函數,該函數將提供警察使用實體框架的統計信息。圖爲數據庫的結構: enter image description hereC#實體框架LINQ - 創建報告

我的問題是,我無法正常組織多個加入:

Users.Where(w => w.Region == 1321) 
    .Select(s => s.Id) 
    .Join(Added, x => x, y => y.UserId, (x, y) => new 
    { 
     UserId = x, 
     PersonId = y.PersonId, 
     Date = y.AddDate 
    }) 
    .GroupJoin(Status, x => x.PersonId, y => y.PersonId, (x, y) => new 
    { 
     PersonPreviouslyConvicted = y.PersonPreviouslyConvicted, 
     PersonBum = y.PersonBum, 
     PersonJobless = y.Jobless, 

    }).Join(Photos...).Join(More tables...) 

此外,還有一些要合併7桌和計數號碼。在所有表中,外鍵是PersonId。所有需要包裝ReportContainer類型的對象列表的結果。 ReportContainer如下:

public class ReportContainer 
{ 
    public string Name { get; set; } // City or District name 
    public int? SevenDays { get; set; } // Count of the 7 days by column Added.AddDate 
    public int? ThirtyDays { get; set; } // Count of the 30 days by column Added.AddDate 
    public int? Bum { get; set; } //Count Bum 
    public int? Photography { get; set; } //Count Photos 
    public int? PreviouslyConvicted { get; set; } //Count PreviouslyConvicted 
    public int? Jobless { get; set; } //Count Jobless 

} 
+0

我會建議使用sql查詢這7個表內連接ef會有一些性能影響。當你的數據增長時,它將會很有效率。 你也可以打破單個查詢來優化EF。基準和優化是2做的最好方法 – Eldho

回答

0

我會得到firstdate這樣我就可以。減去7天,30天

var firstdate = Added.Where(a => a.Id == 1).Select(d => d.Date); 

,然後加入用戶,添加,狀態和照片

Users.Where(w => w.Region == 1321) 
    .Select(s => s.Id) 
    .Join(Added, a => a, s => s.UserId , (a, s)=> new 
    { 
     UserId = a.UserId, 
     PersonId = s.PersonId, 
     SevenDays = s.AddDate >= firstdate.AddDays(-7), 
     ThirtyDays = s.AddDate >= firstdate.AddDays(-30), 
    }) 
    .Join(Status, s => s.PersonId, y => y.PersonId, (s, y)=> new 
    { 
     PersonId = s.PersonId, 
     Bum = y.Bum, 
     Jobless = y.Jobless, 
     PreviouslyConvicted = y.PreviouslyConvicted 
    }) 
    .Join(Photos, p => p.PersonId, y => y.PersonId, (p, y) => new 
    { 
     PersonId = p.PersonId, 
     WithPhotos= y.Photo 
    })