How to CHANGE a related object in the graph?

Apr 29, 2015 at 4:46 PM
Lets say I have an object Account, with a BillToAddress, here is the hierarchy of the object.

Account > BillToAddress > City > State > Country

The repository includes the full BillToAdress when reading like so:
public static Account GetByAccountNumber(
    this IRepository<Account> repository, 
    string accountNumber)
    return repository
        .Include(e => e.BillToAddress.City.State.Country)
        .FirstOrDefault(e => e.AccountNumber == accountNumber);
This works well, but what is the preferred way of setting a new Country on the object? I tried just setting the Account.BillToAddress.City.State.Country = null, then Account.BillToAddress.City.State.Country.CountryId = myNewCountryId then
Account.ObjectState = ObjectState.Modified
...but I get a DbUpdateException due to relation.

Do I have to read the Country by Id from the repository, then set like so?
Account.BillToAddress.City.State.Country = newCountryReadFromDB
Account.BillToAddress.City.State.Country.ObjectState = ObjectState.Modified?

I wanted to avoid the read if I already know the CountryId.

Thanks for the awesome framework!!! Great job!
Apr 29, 2015 at 7:08 PM
This does in fact work, I had another issue that was preventing me from successfully changing the related entity.
I just have to null the related entity, assign to the id, set the object state, then save like so:
AccountClient client = new AccountClient();
var account = client.GetByAccountNumber("000010");

account.BillToAddress.City.State.Country = null;
account.BillToAddress.City.State.CountryId = 69;
account.BillToAddress.City.State.ObjectState = ObjectState.Modified;
May 12, 2015 at 5:41 PM
BBauer42 is correct you must set the ObjectState for every entity in your object graph, please have a look at the Customer integration test which examples this, last but not least it's best practice to call InsertOrUpdateGraph for this use case.
Marked as answer by lelong37 on 5/12/2015 at 9:41 AM