Skip to content

Inserting 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);

    var customerForInsertGraphTest = new Customer
    {
        CustomerID = "LLE38",
        CompanyName = "CBRE",
        ContactName = "Long Le",
        ContactTitle = "App/Dev Architect",
        Address = "11111 Sky Ranch",
        City = "Dallas",
        PostalCode = "75042",
        Country = "USA",
        Phone = "(222) 222-2222",
        Fax = "(333) 333-3333",
        ObjectState = ObjectState.Added,
        Orders = new[]
        {
            new Order()
            {
                CustomerID = "LLE38",
                EmployeeID = 1,
                OrderDate = DateTime.Now,
                ObjectState = ObjectState.Added,
            }, 
            new Order()
            {
                CustomerID = "LLE39",
                EmployeeID = 1,
                OrderDate = DateTime.Now,
                ObjectState = ObjectState.Added
            }, 
        }
    };

    customerRepository.InsertOrUpdateGraph(customerForInsertGraphTest);
    unitOfWork.SaveChanges();
}