Skip to content

Deep Loading a Complex Object Graph

Long Le edited this page Sep 20, 2017 · 2 revisions

Note: The following are typically injected: IRepositoryProvider, IDataContextAsync, IDataContextAsync, IRepository, IRepositoryAsync vs. manually instantiated as they are in the code samples below.

private readonly IRepositoryProvider _repositoryProvider = new RepositoryProvider(new RepositoryFactories());

using (IDataContextAsync context = new NorthwindContext())
using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context, _repositoryProvider))
{
    IRepositoryAsync<Customer> customerRepository = new Repository<Customer>(context, unitOfWork);
                
        customerForUpdateDeleteGraphTest = customerRepository
        .Query(x => x.CustomerID == "LLE38")
        .Include(x => x.Orders)
        .Select()
        .SingleOrDefault();

    // Testing that customer was created
    Assert.AreEqual(customerForUpdateDeleteGraphTest.CustomerID, "LLE38");

    // Testing that orders in customer graph were created
    Assert.IsTrue(customerForUpdateDeleteGraphTest.Orders.Count == 2);

    // Make changes to the object graph while in this context, will save these 
    // changes in another context, testing managing states between and/or while disconnected
    // from the orginal DataContext

    // Updating the customer in the graph
    customerForUpdateDeleteGraphTest.City = "Houston";
    customerForUpdateDeleteGraphTest.ObjectState = ObjectState.Modified;

    // Updating the order in the graph
    var firstOrder = customerForUpdateDeleteGraphTest.Orders.Take(1).Single();
    firstOrder.ShipCity = "Houston";
    firstOrder.ObjectState = ObjectState.Modified;

    // Deleting one of the orders from the graph
    var secondOrder = customerForUpdateDeleteGraphTest.Orders.Skip(1).Take(1).Single();
    secondOrder.ObjectState = ObjectState.Deleted;
}