GriffinHeart
GriffinHeart

Reputation: 450

Adding entity in the domain service insert method

I have two entities, Parent and Child, at the client side i create Parent and then call context.submitChanges

At the server side in the InsertParent(Parent parent) i do:

InsertParent(Parent parent)
{
   Child child = this.ObjectContext.Childs.CreateObject();
   parent.child = child;

   if ((parent.EntityState != EntityState.Detached))
   {
     this.ObjectContext.ObjectStateManager.ChangeObjectState(parent, EntityState.Added);
   }
   else
   {
    this.ObjectContext.Parents.AddObject(parent);
   }
}

Now i'm having two problems.

Before the if else, Parent.id is 0 and after its still 0 but in the database its populated.

The other one is, Child gets saved but Child.ParentId is 0.

I'm not understanding why.

Whats the correct way to achieve this behaviour? should i call SaveChanges() on the context directly?

Upvotes: 0

Views: 1173

Answers (2)

BigL
BigL

Reputation: 1631

Yes you should use the SaveChanges() because that's what persist your data into the Database.

Very Easy Example

You also need to check the parents.Id column and childs Id column that they are set as identity and as primary keys, and the relations between the two tables.

Upvotes: 0

Brian Cauthon
Brian Cauthon

Reputation: 5534

Check to make sure the StoreGeneratedPattern property on Parent.Id in your edmx is set to Identity. That should make sure it gets updated with the new value on inserts.

I'd also wrap this in a transaction so you can add your child after the parent id is set.

using(var scope = new TransactionScope()){
    ObjectContext.Parents.AddObject(parent);
    ObjectContext.SaveChanges(); //parent.id assigned
    parent.child = ObjectContext.Child.CreateObject();
    ObjectContext.SaveChanges();
    scope.Complete(); // commit transaction
}

Upvotes: 1

Related Questions