0

I am trying to amend a c# project. I am a vb.vet programmer so having a few issues as I am new to linq. I am trying to run a Linq to Entity query. I want to select the MapEast where town = town. I keep get an error The specified cast from a materialized System.Decimal' type to the 'System.Int32' type is not valid.. I would like to put a max(1) in here too so it returns only the highest number.

var topEast = 0;
try
{
    topEast = this._uow.Addresses
            .Where(a => 
                a.Town.Trim().ToUpper() == town.Trim().ToUpper())
            .Select(m => m.MapEast).FirstOrDefault ();
    return -1;
}
catch
{
    return -1;
}

Thanks

1
  • 1
    Not an answer but a major issue with your code example: You should never call toUpper() or toLower() on a column as part of a LINQ to Entities query. It will produce a massive performance hit. You can use .Where(a => a.Town.Equals(town, StringComparison.OrdinalIgnoreCase) instead. Commented May 20, 2014 at 14:27

1 Answer 1

3

var is used for implicitly typed local variable. When you defined var topEast = 0;, topEast was implicitly assigned type int, and not decimal as per your query. You can fix it by explicitly defining topEast as decimal.

decimal topEast = 0;

I would like to put a max(1) in here too so it returns only the highest number.

Not really sure what you are trying to return, because you are returning -1 from try as well as catch block. If you are trying to return the Max value of MapEast field then you will need Enumerable.Max, otherwise FirstOrDefault would return the first item or null based on criteria.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Habib. I still have the same error. I did try decimal topEast = 0; earlier when I want trying to figure out the error and I still got the cast error. I have just tried it again and I do still have the same error. The return -1; is only for testing purposes I eventually need to return an int after I have processed the map coordinates.
@Easty, what is the type of MapEast is it decimal or Nullable<decimal> / decimal? ?
Hhmmm that is maybe closer to my problem. I have looked in the addresses entity and I see public int MapEast { get; set; } yet the SQL DB is Decimal(8,0). However I do have a linq query working correctly this._uow.Addresses.Where(a => a.Street.Trim().ToUpper().Contains(street.Trim().ToUpper())).Where(a => a.PostCode.Trim().ToUpper() != "N\\A").GroupBy(m => new { m.Street, m.Town, m.PostCode }).Select(m => new Street() { MapEast = m.FirstOrDefault().MapEast, MapNorth = m.FirstOrDefault().MapNorth, Details = m.Key.Street + " " + m.Key.Town + " " + m.Key.PostCode }).AsEnumerable();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.