Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'WhereListIterator`1[Web.Model.Appointment]' to type 'Web.Model.Appointment'

This is a code fragment from my controller

[HttpPost]
public ActionResult Cancel(string id,FormCollection collection)
{
   //This is how I would like to declare appt but I cannot seem to correctly pass id into this method
   //var appt = Application.Session.GetObjectFromOid<Appointment>(new ObjectId(id));

   //I am trying to do it this way instead but I get an error
   var appt = (Appointment)Application.Appointments.Where(a=>a.Id.Equals(collection["Id"]));
   .....
}

This is the error that I get:Unable to cast object of type 'WhereListIterator`1[Web.Model.Appointment]' to type 'Web.Model.Appointment'.

This is my view:

<input type="button" value="Save" onclick="updateCancel(); return false;" /><button>Save</button>

and this is my function

 function updateCancel() {
    $('#cancel').ajaxSubmit({

    });
    }

So why am I getting this error? OR is there a way to pass Model.Data.Id into my function so that I can just use id instead?

like image 910
caradrye Avatar asked Mar 08 '12 22:03

caradrye


2 Answers

The Where-clause returns an iterator. Select what you want to use instead. I.e., if you expect only one result, you can use FirstOrDefault. You can also use an index, like [1].

var appt = (Appointment)Application.Appointments.Where
     (a=>a.Id.Equals(collection["Id"]))
     .FirstOrDefault();

Note that FirstOrDefault returns null when the item is not found, so be sure to check the result value.

PS: you probably don't need your cast there. Without (Appointment, from the error in your title, this should just work, because the items in the list are of type Appointment.

like image 163
Abel Avatar answered Nov 20 '22 15:11

Abel


This is what I ended up using and it worked.

var appt = Application.Session.GetObjectFromOid<Appointment>(new ObjectId(id));
like image 1
caradrye Avatar answered Nov 20 '22 14:11

caradrye