in my database there are 3 tables
CustomerType
CusID
EventType
EventTypeID
CustomerEventType
CusID
EventTypeID
alt text http://img706.imageshack.us/img706/8806/inserevent.jpg
Dim db = new CustomerEventDataContext
Dim newEvent = new EventType
newEvent.EventTypeID = txtEventID.text
db.EventType.InsertOnSubmit(newEvent)
db.SubmitChanges()
'To select the last ID of event'
Dim lastEventID = (from e in db.EventType Select e.EventTypeID Order By EventTypeID Descending).first()
Dim chkbx As CheckBoxList = CType(form1.FindControl("CheckBoxList1"), CheckBoxList)
Dim newCustomerEventType = New CustomerEventType
Dim i As Integer
For i = 0 To chkbx.Items.Count - 1 Step i + 1
If (chkbx.Items(i).Selected) Then
newCustomerEventType.INTEVENTTYPEID = lastEventID
newCustomerEventType.INTSTUDENTTYPEID = chkbxStudentType.Items(i).Value
db.CustomerEventType.InsertOnSubmit(newCustomerEventType)
db.SubmitChanges()
End If
Next
It works fine when I checked only 1 Single ID of CustomerEventType from CheckBoxList1. It inserts data into EventType with ID 1 and CustomerEventType ID 1. However, when I checked both of them, the error message said
Cannot add an entity that already exists.
Any suggestions please? Thx in advance.
Did you change the
EventIDbefore you pressed the button again. To me it looks as you did not. This would result that the code tries to insert the event with theID 1into the database, although, it is already there.Maybe try increasing the event ID automatically or check whether the event is alreay present before trying to insert it.
Edit:
OK, here is what I think you want to do … if I understood it correctly (it’s in C# as I am more fluent in that language – however you should be able to easily convert the algorithm to VB – so just take it as pseudo code):
Two things I noticed:
EventTypeand then selecting the last event type based upon the id. This may not result in the item you just added.SubmitChangesafter eachInsertOnSubmit. TheDataBaseContextimplementaton holds the inserted objects for you and you can reference them. Then you do a single submit to commit all changes. Note, however, in some complex circumstances a separateSubmitChangesis necessary, but this is rarely the case.