Inserting a many-to-many relationship RRS feed

  • Question

  • Hi,

    I'm having trouble inserting a many-to-many relationship into my SQL Server 2008 Express database through EF4.
    The database model is quite straightforward containing the tables:

    -- EmployeeID [GUID] [PK]
    -- ...

    -- TaskID [GUID] [PK]
    -- ...

    A junction table:

    -- EmployeeID [GUID] [PK]
    -- TaskID [GUID] [PK]
    {no other fields}

    Using VS2010 RC, I created an EDMX file and the entities seems fine (the junction table is left out):

    ||Employee|| * ----- * ||Task||

    Also, I created Self-Tracking Entities and your basic Client - WCF Service solution.
    I use the following code to create a new Employee with an existing Task

    Using SC = New CompanyServiceReference.CompanyServiceClient
        Dim TaskID As New Guid("38178c84-08e2-417f-b8b8-e6f92efc24a9")
        Dim ExistingTask As Task = SC.GetTask(TaskID)
        If Not IsNothing(ExistingTask) Then
        End If                    
    End Using

    And the InsertEmployee method at the server:

        Public Sub InsertEmployee(ByVal NewEmployee As STECompanyTypes.Employee) Implements ICompanyService.InsertEmployee
                Using CompanyEnts = New CompanyEntities
                End Using
            Catch ex As Exception
            End Try
        End Sub

    The Task is retrieved but then I get the exception:

    Violation of PRIMARY KEY constraint 'PK_Task'. Cannot insert duplicate key in object 'dbo.Task'.
    The statement has been terminated."

    1-to-many relationships seem to be beworking fine, only the many-to-many relationship is giving me trouble.
    Any idea what I'm doing wrong?


    Thursday, February 25, 2010 2:36 PM


  • Found the solution.

    At the server component I needed to replace




    in the InsertEmployee() method and then it worked.

    I would have thought the AddObject() method to be the logical approach in the case of insertion, but ApplyChanges() seems to be the end-all/be-all solution.

    • Marked as answer by Henk S Friday, February 26, 2010 11:05 AM
    Friday, February 26, 2010 11:04 AM