What I’m trying to do is to create a custom type, with a custom attribute that will store both Id and Name from a record. (Something like “223 – Robert Smith”). This is what I’m doing:
return (from c in db.Credores
where c.Status == true
select new CredorCompleto
{
Id = c.Id,
Nome = c.Nome,
NomeCompleto = c.Id + c.Nome,
CNPJ = c.CNPJ
}).ToList();
Update: Definition for ‘CredorCompleto’
public class CredorCompleto
{
public string NomeCompleto { get; set; }
public string CNPJ { get; set; }
public string Nome { get; set; }
public int Id { get; set; }
}
This is what I’m getting:
Unable to cast the type
System.Int32to typeSystem.Object. LINQ to Entities only supports casting Entity Data Model primitive types.
Your comment on @Moon’s answer provides an important clue:
The problem might be that
db.Credoresis anIQueryable, and not just anIEnumerable. So when your LINQ to SQL provider tries to analyse your original query, it comes upon a bit that it does not recognise, and does not know how to translate to a SQL query.I suppose the LINQ to SQL provider has problems converting your concatenation
c.Id + c.Nomeinto a valid SQL statement, possibly because the former is anintand the latter astring.What’s for sure is that it definitely doesn’t know how to transform a call to
string.Format()to SQL (which is not surprising, since SQL doesn’t have that function).So you could try to execute the SQL query before you perform .NET-specific logic on it. Try this:
The call to
.AsEnumerable()— and a call to.ToList()is probably required also, IIRC — will trigger the execution of the SQL query. Everything after that operates on an in-memoryIEnumerable, not on aIQueryable. This means that after the.ToList(), LINQ will do no more smart code analysis, or attempt to transform the remaining operators to SQL.