by Louis-Philippe
3. January 2009 22:43
Recently i was working on a project where i was using Entity Framework as the data layer. It's the first project i'm working with it. In one of my query I wanted to output some fields merge in one fields like the following query:
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable GetListJoueursByClubId(int clubId)
{
var query = from joueur in this.Joueurs
where joueur.Clubs.Id == clubId
orderby joueur.Clubs.Nom
select new { Id = joueur.Id, NomComplet = joueur.Nom + ", " + joueur.Prenom
+ " " + (joueur.Numero ?? 0) };
return query;
}
But I was always getting errors related to casting.
There was many solutions that could be applied. But one solution to solve the issue at the query level, it's to use a sub query. This way the first query will be executed in memory, and Linq will know the type of the object we are working with and Linq will be able to cast the object properly.
[DataObjectMethod(DataObjectMethodType.Select)]
public IEnumerable GetListJoueursByClubId(int clubId)
{
var query = from joueur in this.Joueurs
where joueur.Clubs.Id == clubId
orderby joueur.Clubs.Nom
select new { Id = joueur.Id,
Nom = joueur.Nom,
Prenom = joueur.Prenom,
Numero = joueur.Numero
};
return from joueur in query.ToList()
select new { Id = joueur.Id, NomComplet = joueur.Nom + ", " + joueur.Prenom
+ " " + (joueur.Numero ?? 0) };
}
I hope this will help you, if you face this kind of issue.
Regards,
Louis-Philippe
60215146-8700-430c-9cab-9f2ed5b3fe0e|0|.0
Tags: