2013-07-29 20 views
0

我想從SQL Server數據庫中獲取數據。在實體框架中使用linq時獲取類型轉換錯誤

我在我的數據庫中有一個名爲Standard的表。它有三列StandardID,StandardNameDescription

我有一個組合框在我填補StandardName

值以下是代碼:

Using db As New SchoolDBEntities 
    ComboSelectStandardToEdit.DataSource = db.Standards.ToList() 
    ComboSelectStandardToEdit.ValueMember = "StandardID" 
    ComboSelectStandardToEdit.DisplayMember = "StandardName" 
End Using 

現在我有2個文本框稱爲txtStandardNametxtDescription

我想根據組合框中選定的StandardName填充這兩個文本框的值。

這裏是我試過的代碼:

Using db As New SchoolDBEntities 
      Dim standard = From s In db.Standards 
          Where s.StandardId = CInt(ComboSelectStandardToEdit.SelectedValue) 
          Select s 

      txtStandardName.Text = CType(standard, Standard).StandardName 
     End Using 

但不幸的是我得到了錯誤:

無法投類型的對象System.Data.Entity.Infrastructure.DbQuery `1[EF_WinForms_VB.Standard]' to type 'EF_WinForms_VB.Standard'.

回答

2

嘗試使用

Dim standard = (From s In db.Standards 
    Where s.StandardId = CInt(ComboSelectStandardToEdit.SelectedValue) 
    Select s) 
    .FirstOrDefault 

txtStandardName.Text = standard.StandardName 

您的Linq查詢當前正在回退可能包含多個條目的投影。通過明確請求投影的第一個對象,在訪問它的值之前,您不需要投射標準。

+0

T在運行時出現此錯誤:無法創建類型爲'System.Object'的常量值。只有原始類型或枚舉類型在此上下文中受支持。 – Khushi

+0

似乎這可能與你的where子句有關,在某一點你正在使用'StandardID',而在另一個你正在使用的'StandardId'不是對象 – Claies

+0

@ user2524507的屬性:你probaby必須提取'在Dim標準行之前的CInt轉換:Dim standardId = CInt(ComboSelectStandardToEdit.SelectedValue),然後是Where子句:其中s.StandardId = standardId – Slauma

1

嘗試使用

昏暗標準=(來自S對在db.Standards.AsEnumerable 凡s.StandardId = Convert.ToInt32(ComboSelectStandardToEdit.SelectedValue) 選擇多個) .FirstOrDefault

txtStandardName.Text = standard.StandardName

希望它有幫助。