Casting issues with Linq and Entity Framework

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.
image
 
 
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
 

Tags:

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author

Louis-Philippe Pinsonneault is a senior .NET developer and trainer at Runatserver Consulting. He has over 9 years of experience with . NET technology. He is a certified Microsoft Certified Professional Developer (MCPD) and a Microsoft Certified Technology Specialist .NET Framework 3.5 ASP.NET Application. He also teaches ASP.NET at Technologia, Montréal.

Microsoft Certified Professional Developer

Microsoft Certified Technology Specialist

View Louis-Philippe's profile on LinkedIn

Page List