none
Entity Model Inserting data in the wrong order RRS feed

  • Question

  • Hi,

    I have a problem when executing the SaveChanges

    I have 2 tables Jobs and JobAddress.

    Jobs has the following structure (JobID uniqueidentifier (PK), field1  int , field2 int etc)

    JobAddress has the following structure (JobAddressID uniqueidentifier (PK), JobID uniqueidentifier (PK), field1  int , field2 int etc)

    there is a Foreign Key relationship between the two tables using the JobID Field.

     

    I added a Entity Data model and selected the two tables.

    The first thing that I noticed is that it did not automatically relate the two tables. So I had to set the manually associate the two objects.

    My Code is like this

     

    private void ProcessData()

    {

          Entities.MyEntities db = new Entities.MyEntities();
          job = db.CreateObject<Entities.job>();
          db.job.AddObject(job);

          job.JobID = GetNewID();

          job.field1 = "test value";

          MyEntities.jobAddress add = new MyEntities.jobAddress();

          add.JobAddressID = GetNewID();

          add.StreetName = "My Street Name";

          add.JOb = job;

          db.Connection.Open();

          db.SaveChanges();

     

    and error occurs saying that the foreign key constraint was not satisfied.

    I was running sql profiler and so that the first insert method was for the JobAddress instead of the Job Table.

     

    }

    How do I ensure that the entity saves the parent objects first before the child objects.

     

    Cheers!


     

    Thursday, February 10, 2011 1:53 AM

Answers

  • Hello phDramos,

     

    Welcome to the MSDN Forum and thanks for posting here!

    According to your description, it looks like you could be trying to save an invalid entity - one that does not satisfy your constraints. At the database level, I would guess that you have a foreign key constraint on a field that is not allowed to be NULL. I guess the real problem is that whenever an invalid entity object is added with the method AddTo(entityObj), any further call to SaveChanges() will try to add that object into the context.

    Please see this thread, I think it can help you:

    http://stackoverflow.com/questions/1962689/weird-constraint-exception-with-entity-framework

    Thanks for your understanding and support.

     

    Have a nice day, 


    Jackie Sun [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.

    Monday, February 14, 2011 6:46 AM
    Moderator