Linq to实体查询中的InvalidCastException

时间:2013-06-01 13:03:14

标签: vb.net linq

我正在为我的部门申请工作。我遇到了一个大问题。

我正在尝试获取在ListBox控件上选择的名称的主键。在加载表单时,将从数据库中的查询填充此ListBox控件。下面是用于填充ListBox控件的查询。

Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
Order By officer.First_Name Ascending
Select officer.First_Name.ToUpper & " " & officer.Last_Name.ToUpper

lstFullname.DataSource = findOfficer.ToList
lstFullname.DisplayMember = "FullName"

查询工作正常,ListBox按预期填充。问题是我试图获取所选ListBox项的主键的值。我尝试检索的主键值是一个整数值,它被设置为identity

以下是我的数据库摘要。

Exam_Officer

Officer_ID as int which is the primary key and is also set as an identity column
First_Name as nvarchar
last_Name as nvarchar

另一张表是Result_Submitted, 它的列是:

sn as integer primary key and an identity column
Officer_ID as an int and is a foreign key to the Table Exam_Officer
Result_Submitted as nvarchar
Outstanding_Result as nvarchar

这是我试图用来从Windows窗体的ListBox控件的officer_ID属性中获取SelectedItem的代码。

Dim selectedOfficer As Exams_Officer = DirectCast(lstFullname.SelectedItem,     Exams_Officer)
Dim selectedOfficerID As Integer = selectedOfficer.Officer_ID
The code dosen't work it throws an error on the first line (directcast method)

System.InvalidCastException was unhandled
Message=Unable to cast object of type 'System.String' to type    'EXAMINATION_OFFICER_PAYMENT.Exams_Officer'.
Source=EXAMINATION OFFICER PAYMENT

我很困惑,不知道还能做什么。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

说实话,我很惊讶,因为FullName不是String的财产,所以我甚至会显示它。看看你的代码:

Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
Order By officer.First_Name Ascending
Select officer.First_Name.ToUpper & " " & officer.Last_Name.ToUpper

您正在选择全名 - 因此您的代码结果只是名称,而不是原始官员。我怀疑你想要:

Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
                  Order By officer.First_Name Ascending

lstFullname.DataSource = findOfficer.ToList
lstFullname.DisplayMember = "FullName"

此时,你有一个官员列表而不是字符串列表。这是假设FullName是你的军官类型的属性。如果不是,您可能希望投影到一个列表,在该列表中您在一个属性中执行字符串连接,但将原始官员保留在另一个属性中。例如:

Dim examinationOfficer As New ExamOfficerPayEntities
Dim findOfficer = From officer In examinationOfficer.Exams_Officer
    Order By officer.First_Name Ascending
    Select New With {
        .FullName = officer.First_Name.ToUpper & " " _ & officer.Last_Name.ToUpper,
        .Officer = officer
    }

lstFullname.DataSource = findOfficer.ToList
lstFullname.DisplayMember = "FullName"

然后,您需要提取Officer属性的值以获取官方对象本身。

答案 1 :(得分:0)

一般来说,执行此操作的方法是将官员添加到ListBox并覆盖Officer的ToString()方法以返回FullName,或绑定并将DisplayMember设置为Fullname。和Jon Skeet一样,我不确定你发布的代码为何会起作用......

然后你可以做

Dim selectedOfficer As Exams_Officer = DirectCast(lstFullname.SelectedItem, Exams_Officer)

Exams_Officer.OfficeID没问题。

当你向一名军官施放一个字符串时,上面会向一名官员施放一个对象,这更有可能发挥作用。

请记住,你需要对所有的军官进行实例,并且他们将会记忆犹新。因此,如果有很多和/或官员是一个沉重的对象,性能可能会开始受到影响。 那时最简单的选择是一个只有ID和名称的小类/结构。