Thursday, October 11, 2018

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.Int32]' to type 'System.IConvertible'

 Following is a sample linq query which might cause the problem:

int id = Convert.ToInt32(from ts in db.TShirtSizes where ts.Size == "S" select ts.Id);

You get an error as :

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.Int32]' to type 'System.IConvertible'

What happens is that, in the initial query you get a list of results. If you need to get a single value, do it by changing the code as shown below

int id = Convert.ToInt32((from ts in db.TShirtSizes where ts.Size == "S" select ts.Id).Single());



No comments:

Post a Comment