I have a one-to-many relationship... I am working in a web environment (disconnected environment). Imagine user wanting to update only the parent entity, without having to load all the child entities, is it possible?
This is the code:
public class Parent
{
public int Id { get; set; }
public string Description { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
public Parent Parent { get; set; }
public string Data { get; set; }
}
I want to update description of Parent
with id = 5, the new description is coming from User:
Parent parent = new Parent()
{
Id = 5, // I already know the user Id
Description = "new description from User";
Children = null; // I don't want the children to be changed
}
dbContext.Parent.Attach(parent);
dbContext.Entry(parent).State = EntityState.Modified;
dbContext.SaveChanges();
I am not sure if this is the right approch? will existing Children
be deleted (since the children list is null)?
is it possible?
Yes, you are doing right.
According to your sample
dbContext.Parent.Attach(parent);
dbContext.Entry(parent).State = EntityState.Modified;
dbContext.SaveChanges();
It just effects on parent
table only.