tags:

views:

99

answers:

3
private Incident incident = null;

incident = (Incident)(rdc.Incidents.Where(i => i.ID == ID));

I get the following exception:

Unable to cast object of type 'System.Data.Linq.DataQuery`1[WPF.Incident]' to type 'WPF.Incident'.

I need an instance of Incident to use it like this:

IList listInjury = ((IListSource)incident.Incident_Injuries.OrderBy(m => m.Employee.LastName)).GetList();
+5  A: 

Try:

incident = rdc.Incidents.First(i => i.ID == ID);
Mehrdad Afshari
Thank you. That makes sense and worked.
+4  A: 

The Where method can return multiple results (probably not in your specific case, but in the general case it could), so you'll need to get the first (and presumably only) result with First method like Mehrdad described

Davy8
Thank you for the explanation.
+1  A: 

The code

(Incident)(rdc.Incidents.Where(i =>i.ID == ID))

returns a sequence, IEnumerable<Incident> and you are trying to cast that to type of Incident.That's why you're getting InvalidCastException because those types are not compatible. As Mehrdad suggested, you can use First. However, First would throw an exception if the sequence does not contain any elements. This may or may not be desirable. If exception is not desirable, you can call DefaultOrEmpty which would return the default value for that type if the sequence contains no elements. If Incident is a reference type, the default value would be null and you should add a null check in your code and handle that case appropriately.

Mehmet Aras