I have the following scenario involving 2 classes:
public class Parent
{
[Key]
public int Id {get;set;}
//.. Other properties here
public virtual IList<Child> Children {get;set;}
}
and
public class Child
{
[Key]
public int Id {get;set;}
public int ParentId {get;set;}
//.. Other properties here
[ForeignKey("ParentId")]
public virtual Parent {get;set;}
}
I also have an DbContext with the associated DbSet Children and DbSet Parents and I want to make the following update operation:
//.. Get some Parent instance -> convert it to ParentVM -> do some operations on ParentVM in the Service //layer () -> then try to update it back using EF:
// parentVM now contains a modified version both in the primitive properties and also in the children collection: some children have new values
var parent = ConvertBackToORMModel(parentVM); //converts everything back, including the Children collection
using (var context = new ApplicationDbContext())
{
context.Set<Parent>().AddOrUpdate(parent);
//context.Set<Child>().AddOrUpdate(childModified); // If I do this here, it saves also the modified children back in the DB; but I want this to be **automatic when updating the parent**
context.SaveChanges(); //here, the primitive modified properties are saved in DB, the modified children collection remains the same
}
The problem is that, the above code snippet is generic, which means that I would need to iterate, depending on the object through the Children collection (or all virtual collections, etc.) and call context.Set().AddOrUpdate(childModified); for each one. I want this behavior to be automatic when updating the parent.
Is there any way to do this?
Thanks, Ionut