views:

84

answers:

2

I'm pretty new to the EDM, so bear with me. I have a windows form that has a DataGridView on it that's bound from the EDM I created. I figured out how to update my changes fine, but it's when the user creates a new row that I'm having a problem.

I tried numerous ways and many google searches, but came up with nothing so far.

Here's how the data is loaded:

    Dim boilerID As Integer = DirectCast(ddlBoiler.SelectedValue, Integer)
    Dim countryID As Integer = DirectCast(ddlCountry.SelectedValue, Integer)

    Dim ratings = From r In _Context.Rating _
                 Where r.Boiler.Boiler_ID = boilerID _
                 And r.Country.Country_ID = countryID _
                 Order By r.Sequence _
                 Select r

    RatingBindingSource.DataSource = ratings.ToList()

Also, all I'm doing to save the information right now is the following:

Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
    _Context.SaveChanges()
End Sub

I want the user to be able to use the grid's "new row" feature to add new items to the database instead of having to click a button and open a new dialog. How would this be accomplished?

I can include some of the methods i tried for adding new items if anyone needs to see.

Thanks!

UPDATE: here's one of the methods I tried for adding new objects and the error I receive:

    For Each dgvr As DataGridViewRow In dgvRatings.Rows
        If dgvr.DataBoundItem IsNot Nothing AndAlso CType(dgvr.DataBoundItem, Rating).Rating_ID <= 0 Then

            Dim r As Rating = dgvr.DataBoundItem
            r.Boiler = ddlBoiler.SelectedItem
            r.Country = ddlCountry.SelectedItem

            _Context.AddObject("Rating", r)
        End If
    Next

Error (occurs when calling _Context.SaveChanges()): Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

+1  A: 

you need to use

_Context.MyEntities.AddObject(theNewObject)

This registers the created object to be inserted when calling .SaveChanges()

You didn't give enough information to give a more complete answers, but creating a new entity, and adding it that way is what it comes down to.

Sander Rijken
Thank you for responding. I tried something similar. See my update for the error i'm getting.
AcousticBoom
A: 

Found the issue. In my stored procedure mapping, i had Rating_ID set as a Results Binding. In my stored proc I had the following:

RETURN SCOPE_IDENTITY()

Instead of:

SELECT SCOPE_IDENTITY() AS Rating_ID

I didn't think it was a stored proc issue since i knew the insert was correct (I could run the procedure by itself) and there were no records being inserted. I guess when it didn't find the Rating_ID as part of the result set, it removed the record.

AcousticBoom