How to update related entities using GraphDiff?

c# ef-code-first entity-framework graphdiff

Question

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?

1
7
2/5/2015 10:00:58 AM

Accepted Answer

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();
8
8/25/2016 11:53:11 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