user2156088
user2156088

Reputation: 2420

Runtime error Unable to Cast Object

Getting a runtime error while casting is done. How can it be solved?

public spc GetSc(int ID)
{
    var SC = from items in db.Stable where items.id== ID orderby items.id select items;
    SC.Cast<spc>();
    return (spc)SC; // This line throws the error
}    

Error message:

Unable to cast object of type
'System.Data.Entity.Infrastructure.DbQuery`1[Tool.Models.Transaction.spc]'
to type 'Tool.Models.Transaction.spc'.

Upvotes: 0

Views: 789

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

You're trying to return a single spc from an IQueryable<spc> (which can contain 0 to any spc's) to a single entity.

Either call .Single(OrDefault)() or .First(OrDefault)() on SC.

Upvotes: 3

Related Questions