skip to Main Content

Let’s say We have class parent

    public class Parent {
int Id {get;set;}
Child child {get;set;}
}

And class child

public class Child {
    int Id {get;set;}
    string Info {get;set;}
    }

I create an object of child and save it db

Child child = new Child();
  dbContext.Child.Add(child);
                    dbContext.SaveChanges();

then I create a parent object and assign the created child to parent object(to use it later)

 Parent parent = new Parent();
      parent.child=child;
       dbContext.Parent.Add(parent);
         dbContext.SaveChanges();

The problem after saving the the parent object in the db, I get a duplicated object of child in child Class in the db.
Note that I’m using sql Server as db.

I want to assign the object of child to parent and when I save parent in the db, the parent don’t save the child again, Any solution please?

3

Answers


  1. Chosen as BEST ANSWER

    The only solution I found is to call the save method of the dbcontext only once, (I called it when saving the parent only) otherwise it will save it twice in the database.


  2. Try this

    Parent parent = new Parent();
    var existingChild = dbContext.Child.Find(child.id);
    if (existingChild != null){
        parent.child = existingChild;
    }
    dbContext.Parent.Add(parent);
    dbContext.SaveChanges();
    
    Login or Signup to reply.
  3. To avoid insertion again if it’s already there you can set dbContext as Unchanged after attaching the child object to the context.

    Add the following code after the saving child object.

    dbContext.Entry(child).State = EntityState.Unchanged;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search