在使用实体框架的include语句时,选择特定的列
在使用实体框架的include语句时,选择特定的列
当我需要一个层次关系(父子关系)时,我通常在我的EF查询中使用Include语句。
示例:
DbContext.Customers.Include("Projects");
这样做没问题,但是Customers和Projects实体总是返回所有列。
我知道下面的查询会返回父表中的特定列,但我也想只返回子表中的特定列。如果我在Projects上使用智能感知,它显然是一个集合,并且没有给出要选择的具体属性。
from c in Customers
let Projects = c.Projects.Where (p => p.Notes != null)
where Projects.Any()
select new
{
c.UserName,
Projects
}
我尝试优化查询为下面的代码,但是如你所见,Projects实体是Customers的子实体,因此在查询中没有特定的列可选择。它显然是一个集合。
在使用Include进行查询时,是否有办法只返回每个实体中的特定列?
请注意,我的YeagerTechDB.ViewModels.Customers模型由Customer和Project实体中的所有列组成。
public ListGetCustomerProjects() { try { using (YeagerTech DbContext = new YeagerTech()) { var customer = DbContext.Customers.Include("Projects").Select(s => new YeagerTechDB.ViewModels.Customers() { CustomerID = s.CustomerID, ProjectID = s.ProjectID, UserName = s.UserName, Name = s.Projects., }); return customer.ToList(); } } catch (Exception ex) { throw ex; } }
答案1:对于一个子实体
from c in Customers
let Projects = c.Projects.Where (p => p.Notes != null)
where Projects.Any()
select new
{
c.UserName,
Projects
}
答案2:对于两个子实体
from c in Customers
let highValueP =
from p in c.Projects
where p.Quote != null
select new { p.ProjectID, p.Name, p.Quote }
where highValueP.Any()
from p in Projects
let highValuet =
from t in p.TimeTrackings
where t.Notes != null
select new { t.ProjectID, t.Notes }
where highValuet.Any()
select new
{
c.CustomerID,
Projects = highValueP,
TimeTrackings = highValuet
}
编辑3