user1777964
user1777964

Reputation: 23

How to INSERT into table using Entity Data Model (EDMX)

I am trying to write a button handler in VB.NET that will read rows from a gridview and write them to a DB if a checkbox is checked.

I setup this application to use EntityDataSource and added my .edmx file to a DAL folder. I have the button method written but I do not know enough about EF to know how to handle the data the data from the gridview. Here is my btn_click method:

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

I am fairly new to EDMX but understand VB.net. Any direction would be greatly appreciated.

Upvotes: 2

Views: 2376

Answers (2)

whyoz
whyoz

Reputation: 5246

Thanks to @rs., I was able to figure out my issues. Referring to the accepted answer, for those wondering what .AddToTableNameE() should be in your proj, it's just going to be .Add(x). It's also somewhat a performance hit using .SaveChanges() for every row, you should create a Dim List(Of TableNameE()) and add the "x" to the list, then use .AddRange() like this:

//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()

Upvotes: 0

rs.
rs.

Reputation: 27467

Check this sample code and modify this to match your entities and objects

 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

Upvotes: 1

Related Questions