【发布时间】:2015-04-06 02:42:08
【问题描述】:
在使用 INCLUDE 语句时,我只想从 EF 中的查询中获取特定列,而不是带回所有列。
此外,如果我还想从我的客户对象中带回更短的结果集怎么办。
有没有办法做到这一点?
这是我的查询:
void Main()
{
IEnumerable<Customer> customerProjectsList = GetCustomerProjects();
customerProjectsList.Dump();
}
public List<Customer> GetCustomerProjects()
{
try
{
using (YeagerTech DbContext = new YeagerTech())
{
var customer = DbContext.Customers.Include("Projects");
return customer;
}
}
catch (Exception ex)
{
throw ex;
}
}
编辑
我一直在尝试使用以下查询,但收到“无法将类型 'System.Linq.IQueryable' 隐式转换为 'System.Collections.Generic.ICollection' 的错误。存在显式转换(您是否缺少演员表?)”
这是查询: 无效的主要() { 列出 customerProjectsList = GetCustomerProjects(); customerProjectsList.Dump(); }
public List<CustomerDTO> GetCustomerProjects()
{
try
{
using (YeagerTech DbContext = new YeagerTech())
{
var customerlist = DbContext.Customers.Select(s =>
new CustomerDTO()
{
CustomerID = s.CustomerID,
Projects =
from p in Projects
where p.CustomerID == s.CustomerID && p.Quote != null
select new Project { Description = p.Description, Quote = p.Quote }
}).ToList<Project>();
return customerlist.ToList();
}
}
catch (Exception ex)
{
throw ex;
}
}
如果我在 LINQPad 中将同样的查询作为 C# 语句而不是 C# 程序运行,则查询结果会很好地生成。
我只是想通过这种简单的方法来尝试获取带有特定列的层次结构列表。
var result = (from c in Customers
select new
{
c.CustomerID,
Projects =
from p in Projects
where p.CustomerID == c.CustomerID && p.Quote != null
select new { p.Description, p.Quote }
});
result.Dump();
【问题讨论】:
-
你可以使用投影来做到这一点
-
替换 ToList
();与 ToList(); -
Phillip,恕我直言,必须有一个非常简单的解释,为什么我能够以 C# 语句的形式执行查询,但不能以 C# 程序的形式执行。
-
Philip,我已经用 ToList() 走了那条路,并且遇到了同样的错误.....
-
完全删除 ToList(),最后应该只有一个。您有 2。顺便说一句,您现在已将问题更改为完全不同的问题。您应该从一开始就提供此详细信息或创建一个新问题。您使用 ToList 的那一刻,它就变成了一个普通的 linq 查询,它不再是 IQueryable 了。因此出现错误。
标签: c# linq entity-framework