Hooman Bahreini
Hooman Bahreini

Reputation: 15549

Updating parent entity without changing the children

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

Upvotes: 2

Views: 1519

Answers (2)

Minhaj
Minhaj

Reputation: 188

Simple

var parentDetails = db.Parents.First(w=>w.Id == 5)
parentDetails.Description = "new description from User";
db.Parent.Update(parentDetails)
db.SaveChanges()

and done :)

Another way to update only one column is

db.Table.Attach(Entity)
db.Entry(Entity).Property(x=>x.Description).IsModified=true
db.SaveChanges()

Upvotes: 1

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14198

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.

Upvotes: 1

Related Questions