2012-10-26 37 views
2

我想在VB.NET中編寫一個按鈕處理程序,它將讀取gridview中的行並將它們寫入數據庫(如果複選框被選中)。如何使用實體數據模型(EDMX)插入表

我設置此應用程序使用EntityDataSource並將我的.edmx文件添加到DAL文件夾。我已經編寫了按鈕方法,但我對EF知之甚少,無法知道如何處理gridview中的數據。這是我的btn_click方法:

Private Sub btnGetChecks_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetChecks.Click 
'******************************************** 
'* gets status of checkbox and writes to db * 
'******************************************** 
Dim row As GridViewRow 

Label6.Text = "" 
For Each row In DvsGridView.Rows 
    Dim RowCheckBox As CheckBox = CType(row.FindControl("chkStatus"), CheckBox) 
    If RowCheckBox.Checked Then 
    Label6.Text += row.Cells(5).Text & " Checked " 
    ' Need to write checked data to the db 
    ' ******* WHAT GOES HERE? ******* 
    Else 

    Label6.Text += row.Cells(5).Text & " Unchecked " 

    End If 
Next 
End Sub 

我對EDMX相當新,但瞭解VB.net。任何方向將不勝感激。

回答

1

入住此示例代碼和修改此項,以匹配您的實體和對象

Using db As New DBEntities() 

    'set values here 
    Dim x As New TableNameE() 

    x.col1 = "value1" 
    x.col2 = "value2" 

    db.AddToTableNameE(x) 
    db.SaveChanges() 
End Using 
0

感謝@rs,我能找出我的問題。參考接受的答案,對於那些想知道什麼.AddToTableNameE()應該在你的proj中,它只會是.Add(x)。對於每一行使用.SaveChanges()函數也會有所影響,您應該創建一個Dim List(Of TableNameE())並將「x」添加到列表中,然後使用.AddRange()像這樣:

//creating a data access class is one way to connect to your db by passing in db path 
Dim context As New Namespace.YourContext(New DataAccessClass() With {.Path = aBrowsedForSDFFileTextBoxMaybe.Text}) 
Dim listOfTableObjects As List(Of Namespace.TableObject) = New List(Of Namespace.TableObject) 

    For n = 1 To SomethingRelatedToRows 
    Dim tableObject As New Namespace.TableObject() With { 
        .entityProp1 = TableObject(n).entityProp1, 
        .entityProp2 = TableObject(n).entityProp2, 
        .entityProp3 = TableObject(n).entityProp3, 
        .entityProp4 = TableObject(n).entityProp4, 
        .entityProp5 = TableObject(n).entityProp5, 
        .entityProp6 = TableObject(n).entityProp6 
       } 

     listOfTableObjects.Add(tableObject) 

    Next n 

    //.TableObjects being the DbSet from the ...Context.vb file 
    context.TableObjects.AddRange(listOfTableObjects) 
    context.SaveChanges() 
相關問題