2013-02-13 89 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已()。