Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update related entities using GraphDiff?

I have the following model:

public class Customer
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int AddressId {get; set;}
    public virtual Address Address {get; set;}
    public virtual ICollection<CustomerCategory> Categories {get; set;}
}

public class CustomerCategory
{
    public int Id {get; set;}
    public int CustomerId {get; set;}
    public int CategoryId {get; set;}
    public virtual Category Category {get; set;}
}

public class Address
{
    public int Id {get; set;}
    public string Street{get; set;}
    public virtual PostCode PostCode {get; set;}
}

From the above, and using GraphDiff, I want to update the customer aggregate as follows:

dbContext.UpdateGraph<Customer>(entity, 
            map => map.AssociatedEntity(x => x.Address)
                      .OwnedCollection(x => x.Categories, with => with.AssociatedEntity(x => x.Category)));

But the above is not updating anything!!

What is the correct way to use GraphDiff in this case?

like image 910
Ivan-Mark Debono Avatar asked Feb 05 '15 10:02

Ivan-Mark Debono


1 Answers

GraphDiff basically distinguishes two kinds of relations: owned and associated.

Owned can be interpreted as "being a part of" meaning that anything that is owned will be inserted/updated/deleted with its owner.

The other kind of relation handled by GraphDiff is associated which means that only relations to, but not the associated entities themselves are changed by GraphDiff when updating a graph.

When you use the AssociatedEntity method, the State of the child entity is not part of the aggregate, in other words, the changes that you did over the child entity will not be saved, just it will update the parent navegation property.

Use the OwnedEntity method if you want to save tha changes over the child entity, so, I suggest you try this:

dbContext.UpdateGraph<Customer>(entity,  map => map.OwnedEntity(x => x.Address)
                                                   .OwnedCollection(x => x.Categories, with => with.OwnedEntity(x => x.Category)));
dbContext.SaveChanges();
like image 131
octavioccl Avatar answered Nov 13 '22 03:11

octavioccl