Select Max in Linq to Entities / Entity SQL with type conversion

17,932

The Cast method is supported in LINQ to Entities for primitive types. Use that.

Share:
17,932
andrej351
Author by

andrej351

Updated on June 14, 2022

Comments

  • andrej351
    andrej351 almost 2 years

    I'm trying to create some CRUD functionality for a legacy database and using the Entity Framework as an ORM tool. One table, 'Sites', has a Guid type 'Id' column which is never seen by the users and an integer type 'SiteId' which the users use to identitfy a Site.

    For god knows what reason the numeric SiteId column is of type varchar(10) in the database, but every SiteId in there is an integer and all future SiteIds will also be integers.

    For the purpose of generating a new, unique, integer type SiteId, how can i do what is effectively a 'SELECT MAX(SiteId)' using Entity SQL or Linq to Enities??

    In other words, how can i convert every value in a column from varchar(10) into an int and select the maximum value from that set??

    This looked promising but linq can't convert the parse into a "store procedure"...

    int x = entities.Sites.Max(s => int.Parse(s.SiteId));