Linq要列出,只从DB中选择四列?

时间:2015-09-12 15:54:28

标签: c# .net entity-framework linq anonymous-types

我的表有超过15列,我只想检索那些列的four以存储在内存中。但是,尝试以下方法时,会出现错误cannot explicitly convert List to IEnumerable。这也是正确的做法吗?有一种感觉我错过了where子句或什么? CompanyID是索引。

IEnumerable<Company> company = _db.Company.Select(a => new
{
    CompanyId = Convert.ToString(a.CompanyId),
    CompanyType = a.CompanyType,
    CompanyName = a.CompanyName,
    Email = a.Email
}).ToList();

2 个答案:

答案 0 :(得分:2)

您使用Select语句创建Anonymous Type,但无法将List<definedAnonymousType>转换为IEnumerable<Company>

使用var代替IEnumerable<Company>

var company = _db.Company.Select(a => new
{
    CompanyId = Convert.ToString(a.CompanyId),
    CompanyType = a.CompanyType,
    CompanyName = a.CompanyName,
    Email = a.Email
}).ToList();

然后您的company类型将为List<definedAnonymousType>

答案 1 :(得分:0)

您可以使用所需的确切属性创建CompanyLite dto并将数据转换为

var companyLite = _db.Company.Select(a => new CompanyLite 
{
   CompanyId = Convert.ToString(a.CompanyId),
   CompanyType = a.CompanyType,
   CompanyName = a.CompanyName,
   Email = a.Email
}).ToList();