none
Cannot insert duplicate key in object 'dbo.User'.\r\nThe statement has been terminated RRS feed

  • Question

  • I have a user table. there are references to this table from other tables for fields such as CreatedBy.

    Problem is, when I am inserting a row of another table (say 'x'), it tries to insert a new user into the user table.

    What it should be doing is insert a row into table 'x' with CreatedBy as the existing user.

    Using Entity Framework 4. Anyone faced a problem like that before?


    Nilotpal
    Tuesday, August 16, 2011 6:05 PM

Answers

  • No I didn't use CreateUser or New. The problem was that since there was a WCF Layer in between, I was losing the context. So Entity Framework always thought that the User Object is a new one, since I am passing the CreatedBy from across the WCF Wire.

    I think I have figured out the solution. I am afraid I cannot show the real code here due to proprietory issues, but I am showing some dummy code of what I am planning to do.

     

    you can expose foreign key properties on entity types and define relationships through foreign keys. The Include foreign key columns in the model option in the Entity Data Model Wizard is selected by default. When this option is selected, the generated entity objects have scalar properties that map to foreign key columns.

    Foreign key properties allow you to create or modify a relationship without querying for the principal object. When you include foreign key properties, you can still modify a relationship by updating the reference to the principal object on the dependent or adding a dependent object to a collection on the principal object.

     

    The following demonstrates a simple communication between a client and a service, where the client requests an object from the service, the client updates the object and calls the service to save the changes to the database.

    The service defines two methods:

    static private StudentGrade GetOriginalValue(intID)
    {

        StudentGrade originalItem;
        using(SchoolEntities context = newSchoolEntities())
        {
            originalItem = context.StudentGrades.Where(g => g.EnrollmentID == ID).FirstOrDefault();
            context.Detach(originalItem);
        }
        returnoriginalItem;
    }

     

    static private voidSaveUpdates(StudentGrade updatedItem)
    {
        using(SchoolEntities context = newSchoolEntities())
        {
            // Query for the StudentGrade object with the specified ID.
            var original = (from o incontext.StudentGrades
                             whereo.EnrollmentID == updatedItem.EnrollmentID
                             selecto).First(); 

            // Apply changes.
            context.StudentGrades.ApplyCurrentValues(updatedItem); 

            // Save changes.
            context.SaveChanges();
        }
    } 

    The client updates the values of the foreign key properties and sends the updated object to the service:

     // A client calls a service to get the original object.
    StudentGrade studentGrade = GetOriginalValue(3);

     // Change the relationships.
    studentGrade.CourseID = 5;
    studentGrade.StudentID = 10;

    // The client calls a method on a service to save the updates.
    SaveUpdates(studentGrade);


    Nilotpal
    Thursday, August 18, 2011 1:51 PM

All replies

  • Hi Niotpal,

    Welcome!

    Would you please feel free to show your insert code to us?

    I think you used "new" to create a new user who has been in database and insert table(x) with the property of CreatedBy(new user), right?

    The right way to handle this is:

    1. Retrieve the user by the Key from database and let Context track the entity.

    2. Create a new instance of table(X)

    3. Set the GreateBy property.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, August 17, 2011 8:57 AM
    Moderator
  • No I didn't use CreateUser or New. The problem was that since there was a WCF Layer in between, I was losing the context. So Entity Framework always thought that the User Object is a new one, since I am passing the CreatedBy from across the WCF Wire.

    I think I have figured out the solution. I am afraid I cannot show the real code here due to proprietory issues, but I am showing some dummy code of what I am planning to do.

     

    you can expose foreign key properties on entity types and define relationships through foreign keys. The Include foreign key columns in the model option in the Entity Data Model Wizard is selected by default. When this option is selected, the generated entity objects have scalar properties that map to foreign key columns.

    Foreign key properties allow you to create or modify a relationship without querying for the principal object. When you include foreign key properties, you can still modify a relationship by updating the reference to the principal object on the dependent or adding a dependent object to a collection on the principal object.

     

    The following demonstrates a simple communication between a client and a service, where the client requests an object from the service, the client updates the object and calls the service to save the changes to the database.

    The service defines two methods:

    static private StudentGrade GetOriginalValue(intID)
    {

        StudentGrade originalItem;
        using(SchoolEntities context = newSchoolEntities())
        {
            originalItem = context.StudentGrades.Where(g => g.EnrollmentID == ID).FirstOrDefault();
            context.Detach(originalItem);
        }
        returnoriginalItem;
    }

     

    static private voidSaveUpdates(StudentGrade updatedItem)
    {
        using(SchoolEntities context = newSchoolEntities())
        {
            // Query for the StudentGrade object with the specified ID.
            var original = (from o incontext.StudentGrades
                             whereo.EnrollmentID == updatedItem.EnrollmentID
                             selecto).First(); 

            // Apply changes.
            context.StudentGrades.ApplyCurrentValues(updatedItem); 

            // Save changes.
            context.SaveChanges();
        }
    } 

    The client updates the values of the foreign key properties and sends the updated object to the service:

     // A client calls a service to get the original object.
    StudentGrade studentGrade = GetOriginalValue(3);

     // Change the relationships.
    studentGrade.CourseID = 5;
    studentGrade.StudentID = 10;

    // The client calls a method on a service to save the updates.
    SaveUpdates(studentGrade);


    Nilotpal
    Thursday, August 18, 2011 1:51 PM
  • Hi Nilotpal,

    Thanks for sharing your experience here.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, August 19, 2011 9:20 AM
    Moderator