In a Win7 app, I am trying to update several fields in an ADO.NET database table called “Channel”, with an EntitySetMapping Name of “Channels”, using EntityClient in the EF to access SqlServerCe 3.5 (IPManager_DBEntities).
With the VS 2010 IDE, the code compiles fine and Intellisense has no complaints. The format of the Channel datatable is referenced at the bottom as the various fields in a row (selected by Channel “Number”) need to be updated with information passed to it from code which is not shown for the sake of simplicity. Nothing I have Googled during the past several days has solved my Type Casting dilemma. Using LINQ, I get this RunTime Exception:
“Unable to cast object of type ‘System.Data.Objects.ObjectQuery`1 [Manager.Data.Channel]’ to type ‘Manager.Data.Channel'”.
// Update channel status with information parsed from the data packet.
using (IPManager_DBEntities context = new IPManager_DBEntities())
{
Channel thisChannelRow = (Channel)(from CE
in context.Channels
where CE. Number == int.Parse(IDLine[2])
select CE);
// Throwing exception after setting up this query:
// "Unable to cast object of type 'System.Data.Objects.ObjectQuery`1
// [Manager.Data.Channel]' to type 'Manager.Data.Channel'"
// During debug sessions, "thisChannelRow" is null as a result.
MessageBox.Show("thisChannelRow. Channel = " + thisChannelRow.Number );
ThisChannel.StatusID = int.Parse(IDLine[5]);
ThisChannel.Cycle = int.Parse(IDLine[4]);
ThisChannel.Modified = DateTime.Now;
context.SaveChanges();
}
I hope someone has a solution to help me through this predicament.
The LINQ query is returning an object of a type descendant from
IEnumerable<T>, notChannel, even if there is just one item in the sequence. To get the actual item, useFirstOrDefault:Or
First,Single, orSingleOrDefaultif any of those are a better fit.