LP Pinsonneault blog's

Windows 8, Windows Phone, ...

NAVIGATION - SEARCH

Casting issues with Linq and Entity Framework

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
 

Comments (2) -

Andrew Pelt
Andrew Pelt

Zune and iPod: Most people compare the Zune to the Touch, but after seeing how slim and surprisingly small and light it is, I consider it to be a rather unique hybrid that combines qualities of both the Touch and the Nano. It's very colorful and lovely OLED screen is slightly smaller than the touch screen, but the player itself feels quite a bit smaller and lighter. It weighs about 2/3 as much, and is noticeably smaller in width and height, while being just a hair thicker.

Reply

Steam Wallet Hack
United States Steam Wallet Hack

This is a topic which is close to my heart... Thank you! Where are your contact details though?

Reply

Add comment

biuquote
  • Comment
  • Preview
Loading