2013-02-13 149 views
2

我有一個具有以下表的數據庫:多對多EF LINQ

dbo.Administrator 

dbo.Application 

dbo.AdminApplication 

dbo.Proficiency 

dbo.ProficiencyLevel 
  • Administrators中包含1到許多應用。應用程序中包含許多管理員
  • 應用程序包含1對多水平(S)
  • 能力包含1到許多ProficiencyLevels

使用EF代碼首先,AdminApplication沒有被映射爲一個實體,這是什麼原因造成的我的問題。我想回答是:

「返回命名管理員的所有ProficiencyLevels‘danhickman’

在SQL中,查詢應該是這樣的:

Select * from dbo.ProficiencyLevel pl 
inner join dbo.Proficiency p on p.Id = pl.ProficiencyId 
inner join dbo.Application a on a.Id = p.ApplicationId 
inner join dbo.AdminApplication aa on aa.ApplicationId = a.Id 
inner join dbo.Administrator ad on ad.Id = aa.AdministratorId 
where ad.Name = 'danhickman' 

我用下面的C#代碼解決了這個:

 public IQueryable<LobGame.Model.ProficiencyLevel> GetAllByAdminName(string administratorName) 
    { 
     var context = this.DbContext as LobGameDbContext; 
     var admin = context.Administrators.Include(i => i.Applications).Include("Applications.Proficiencies").Include("Applications.Proficiencies.ProficiencyLevels").Single(o => o.Name == administratorName); 
     List<LobGame.Model.ProficiencyLevel> list = new List<ProficiencyLevel>(); 
     foreach (var app in admin.Applications) 
     { 
      foreach (var prof in app.Proficiencies) 
      { 
       list.AddRange(prof.ProficiencyLevels); 
      } 
     } 
     return list.AsQueryable(); 
    } 

它的錯誤我,我要的foreach並添加到列表中我是UNAB以找出在單個LINQ語句中執行此操作的方法。有什麼想法嗎?

回答

2
 return context.Administrators 
        .Single(o => o.Name == administratorName) 
        .Applications 
        .SelectMany(app => app.Proficiencies) 
        .SelectMany(prof => prof.ProficiencyLevels) 
        .ToList() 
        .AsQueryable(); 
1

使用SelectMany()

var queryableList = 
    context.Administrators.Single(o => o.Name.Equals(administratorName)) 
         .SelectMany(adm => adm.Applications.Select(app => app.Proficiencies.SelectMany(prof => prof.ProficiencyLevels))).ToList().AsQueryable(); 
3

使用查詢語法另一種選擇。這在封面下使用了SelectMany。

var queryableList = 
    from admin in context.Administrators 
    where admin.Name = administratorName 
    from app in admin.Applications 
    from proficiency in app.Proficiencies 
    from level in proficiency.ProficiencyLevels 
    select level; 

注意:這將是一個IQueryable,所以你不需要.ToList()AsQueryable已()。