Updating parent entity without changing the children

c# entity-framework entity-framework-6

Question

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)?

1
1
1/13/2020 5:50:18 AM

Accepted Answer

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.

1
1/14/2020 1:31:20 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow