Home > Net >  Save child before parent without duplication c#
Save child before parent without duplication c#

Time:12-29

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?

CodePudding user response:

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();

CodePudding user response:

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;
  • Related