当我需要一个层级(父子)关系时,我通常在我的EF查询中使用Include语句。
示例:
DbContext.Customers.Include("Projects");
这很好,但客户和项目实体总是带回所有列。
我知道下面的查询会带回父表中的特定列,但我也试图只返回子表中的特定列。如果我在Projects上使用intellisense,它显然是一个集合,并没有给出特定的属性来选择。
from c in Customers
let Projects = c.Projects.Where (p => p.Notes != null)
where Projects.Any()
select new
{
c.UserName,
Projects
}
我尝试将查询改进为以下代码,但正如您所看到的,Projects实体是Customers的子实体,因此,在查询中没有要选择的特定列。它显然是一个集合。
在查询中使用“包含”时,是否有办法在每个实体中恢复特定列?
请注意,我的YeagerTechDB.ViewModels.Customers模型由驻留在Customer和Project实体中的所有列组成。
public List<YeagerTechDB.ViewModels.Customers> GetCustomerProjects()
{
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
答案 0 :(得分:12)
检查此link以获取更多详细信息。简而言之,诀窍是使用.Select()和匿名类型来限制所需的列。在下面的示例中,首先Select()实际上是这样做的:
var results = context.Products
.Include("ProductSubcategory")
.Where(p => p.Name.Contains(searchTerm)
&& p.DiscontinuedDate == null)
.Select(p => new
{
p.ProductID,
ProductSubcategoryName = p.ProductSubcategory.Name,
p.Name,
p.StandardCost
})
.AsEnumerable()
.Select(p => new AutoCompleteData
{
Id = p.ProductID,
Text = BuildAutoCompleteText(p.Name,
p.ProductSubcategoryName, p.StandardCost)
})
.ToArray();