-
September 14th, 2012, 09:15 AM
#1
InvalidCastException when getting first result from LINQ query
Greetings!
I am a complete newbie at LINQ. I am trying to get my first simple little application using it to run. It's built in Visual Studio 2008, using DevArt's LinqConnect product to talk to a PostgreSQL database. Here's the function:
Code:
private void dgvCharges_CellClick(object sender, DataGridViewCellEventArgs e)
{
long chargeNumber = Convert.ToInt32(dgvCharges[e.ColumnIndex, e.RowIndex].Value);
var oneChargeSet = from charge in m_context.Charges
where charge.Charge1 == chargeNumber
select charge;
int chargeCount = oneChargeSet.Count();
var oneCharge = oneChargeSet.First();
}
In the debugger, I see that chargeCount is 1, as expected. I believe that the First() function should return an object that contains all of the data members of the charge table in the database: Charge1, BuiltDate, LoadedDate, Cycle, and everything else. This code compiles and starts nicely. But when I invoke the First() method, I get an InvalidCastException. I get the same expression when I try to give First an explicit type:
Code:
private void dgvCharges_CellClick(object sender, DataGridViewCellEventArgs e)
{
long chargeNumber = Convert.ToInt32(dgvCharges[e.ColumnIndex, e.RowIndex].Value);
var oneChargeSet = from charge in m_context.Charges
where charge.Charge1 == chargeNumber
select charge;
int chargeCount = oneChargeSet.Count();
var oneCharge = oneChargeSet.First<AnnealContext.Charge>();
}
Obviously, I don't understand something basic about LINQ. How do I get this to work?
Thanks very much!
RobR
-
September 14th, 2012, 09:58 AM
#2
Re: InvalidCastException when getting first result from LINQ query
Update: If I do not specify an explicit list of fields, I can pass the query object into a data view control, and the control will display the contents of the table as expected. If I want to use the results of the query in my application, I can include an explicit list of fields to return, and it will work. That's probably a good idea anyway. I remain curious, though, why I can't get the simple first form to work.
Here's what's working for me:
Code:
var oneChargeSet = from charge in m_context.Charges
where charge.Charge1 == chargeNumber
select new
{
charge.Charge1,
charge.Loaded_Date,
charge.Purge_Date,
charge.Standby_Date,
charge.Fire_Date,
charge.Off_Date,
charge.Cool_Date,
charge.Cold_Date,
charge.Unloaded_Date
};
var oneCharge = oneChargeSet.First();
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|