0

I have a large table and I need to select some fields not all of them.

I would to do something like this:

select column 2, column3 from tableName order by column2

But I'm trying it and it's doing a error.

public List<RiskCard> GetAllAcitveRiskCardsBasicProperties(Company company)
{
    return GetDbSet<RiskCard>()
       .Where(i => i.Company.CompanyId == company.CompanyId && i.Active == true)
       .OrderBy(o => o.PremisesName)
       .Select(o => new RiskCard { RiskCardId = o.RiskCardId, PremisesName = o.PremisesName}).ToList();
}

The error is;

The entity or complex type 'my.namespace.RiskCard' cannot be constructed in a LINQ to Entities query.

CidaoPapito
  • 572
  • 1
  • 6
  • 21

1 Answers1

0

Try to follow the error message, don't construct an entity in your LINQ to Entities query, you can create an anonymous type instead. Then you can construct the entities in LINQ to object query later on :

var query = GetDbSet<RiskCard>()
           .Where(i => i.Company.CompanyId == company.CompanyId && i.Active == true)
           .OrderBy(o => o.PremisesName)
           .Select(o => new { RiskCardId = o.RiskCardId, PremisesName = o.PremisesName})
           .ToList();

return query.Select(o => new RiskCard { RiskCardId = o.RiskCardId, PremisesName = o.PremisesName})
            .ToList();

Related question : The entity cannot be constructed in a LINQ to Entities query

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
  • Saw this article but what is the signature of a method of type anonymous? I tried `public List MethodName(){ }` And the visual studio complain about the namespace of T. – CidaoPapito Aug 12 '14 at 13:02
  • I haven't tested this, so you don't want to return `RiskCard` as shown in this answer (you want to just return anonymous type instead) or this answer just didn't actually work for you? The signature can be `List` – har07 Aug 12 '14 at 13:09