我有一个包含以下表格的数据库:
dbo.Administrator
dbo.Application
dbo.AdminApplication
dbo.Proficiency
dbo.ProficiencyLevel
使用EF代码首先,AdminApplication未映射为实体,这就是导致我出现问题的原因。我想回答的是:
“返回名为”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();
}
我不得不预先知道并添加到列表中。我无法在单个LINQ语句中找到一种方法。有什么想法吗?
答案 0 :(得分: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()。
答案 1 :(得分:2)
return context.Administrators
.Single(o => o.Name == administratorName)
.Applications
.SelectMany(app => app.Proficiencies)
.SelectMany(prof => prof.ProficiencyLevels)
.ToList()
.AsQueryable();
答案 2 :(得分: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();