3

I've written a LINQ query that should return an int value. but I'm not able to convert this value to int and an exception occured: Unable to cast object of type 'QuickRoutes.DAL.RouteLinq' to type 'System.IConvertible'.
this is my LINQ :

var res = (from p in aspdb.RouteLinqs
                       orderby p.RouteId descending
                       select p).Take(1);

and the exception occures here:

 route.Id =Convert.ToInt32(res.FirstOrDefault());

how can I solve this problem?

1
  • you are selecting a routeLinq object...instead select the property that corresponds to the int value u r interested in Commented Jul 5, 2012 at 6:35

5 Answers 5

10

that is because res.FirstOrDefault() returns a RouteLinqs type object, because you are using select p , you may select a field using select p.FieldName, where FieldName is the property you require for conversion, which is probably RouteId

You may want to query the particular field in your linq query.

var res = (from p in aspdb.RouteLinqs
                       orderby p.RouteId descending
                       select p.RouteId).Take(1); //p.RouteID or any field you want. 

Or with your current query, you may do:

 route.Id =Convert.ToInt32(res.FirstOrDefault().RouteID);
Sign up to request clarification or add additional context in comments.

Comments

3

Looks like you're selecting the max route id, so why not just do:

route.Id = aspdb.RouteLinqs.Max(x => x.RouteId);

Comments

2

This code should work:

route.Id = Convert.ToInt32((res.FirstOrDefault()).FieldName); 

Comments

1

Not sure how your is but RouteLinqs is defined, but perhaps you are looking to select a specific object from the class RouteLinqs.

var res = (from p in aspdb.RouteLinqs
                   orderby p.RouteId descending
                   select p.SomeProperty).Take(1);

In this case p is a single item of RouteLinqs and p.SomeProperty should be your int value.

Comments

0

First make linq :

IQueryable<int> query = (from p in aspdb.RouteLinqs
                           orderby p.RouteId descending
                           select p.Id);

Than run:

 int result = query.FirstOrDefault();

In 1 command:

int result = (from p in aspdb.RouteLinqs
                           orderby p.RouteId descending
                           select p.Id).FirstOrDefault();

Comments

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.