Thursday, February 4, 2010

NHibernate – Create customer repository (Part 9)


Once the base repository is ready, we can create a customer repository for customer domain entity specific functions.
The customer repository implementation looks like
public class CustomerRepository : Repository<Customer, long>, ICustomerRepository
{
    public CustomerRepository() : base() { }
    public CustomerRepository(ISession session) : base(session) { ___Session = session; }

    public override void Add(Customer entity)
    {
        //Insert orders if any
        if (entity.Orders != null && entity.Orders.Count > 0)
        {
            IOrderRepository __orderRepository = new OrderRepository(___Session);
            entity.Orders.ToList().ForEach(x => __orderRepository.Add(x));
        }

        base.Add(entity);
    }

    public override void Save(Customer entity)
    {
        //Insert or update orders if any
        if (entity.Orders != null && entity.Orders.Count > 0)
        {
            IOrderRepository __orderRepository = new OrderRepository(___Session);
            entity.Orders.ToList().ForEach(x => __orderRepository.SaveOrUpdate(x));
        }

        base.Save(entity);
    }

    public Customer GetByName(string name)
    {
        return First(x => x.FirstName == name);           
    }

    ISession ___Session;
}
Unit tests
[TestClass]
public class CustomerOrder_Fixture
{
    [ClassInitialize]
    public static void ClassInitialize(TestContext context)
    {
        ___sessionFactory = new Configuration()
                        .Configure()
                        .AddAssembly(typeof(BaseEntity<long>).Assembly)
                        .BuildSessionFactory();
    }

    [TestInitialize]
    public void TestInitialize()
    {
        using (ISession __session = ___sessionFactory.OpenSession())
        using (ITransaction __transaction = __session.BeginTransaction())
        {
            __customerCollection.ToList().ForEach(x =>
            {
                x.CreatedDate = DateTime.Now;
                x.ChangedDate = DateTime.Now;
                __session.Save(x);
            });

            __productCollection.ToList().ForEach(x =>
            {
                x.CreatedDate = DateTime.Now;
                x.ChangedDate = DateTime.Now;
                __session.Save(x);
            });
            __transaction.Commit();
        }
    }

    [TestCleanup]
    public void TestCleanup()
    {
        using (ISession __session = ___sessionFactory.OpenSession())
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            var __customers = __customerRepository.GetAll();
            __customers.ToList().ForEach(x => __customerRepository.Remove(x));

            IProductRepository __productRepository = new ProductRepository(__session);
            var __products = __productRepository.GetAll();
            __products.ToList().ForEach(x => __productRepository.Remove(x));
        }
    }

    [TestMethod]
    public void can_create_order_for_existing_customer()
    {           
        using (ISession __session = SessionManager.CurrentInstance.Session)
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            IProductRepository __productRepository = new ProductRepository(__session);

            var __customer = __customerRepository.First(x => x.FirstName == "Prajeesh");
            var __product = __productRepository.First(x => x.ModelNumber == "SX20 IS");

            var __order = new Order
            {
                Customer = __customer,
                OrderNumber = "2010Jan08CANON_PRA",
                Products = new HashedSet<Product> { __product },
            };

            __customer.Orders = new HashedSet<Order> { __order };
            __customerRepository.Save(__customer);
        }
    }

    [TestMethod]
    public void can_retrieve_orders_for_customer()
    {
        using (ISession __session = SessionManager.CurrentInstance.Session)
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            IProductRepository __productRepository = new ProductRepository(__session);

            var __customer = __customerRepository.First(x => x.FirstName == "Prajeesh");
            var __product = __productRepository.First(x => x.ModelNumber == "SX20 IS");

            var __order = new Order
            {
                Customer = __customer,
                OrderNumber = "2010Jan08CANON_PRA",
                Products = new HashedSet<Product> { __product },
            };

            __customer.Orders = new HashedSet<Order> { __order };
            __customerRepository.Save(__customer);
        }

        using (ISession __session = SessionManager.CurrentInstance.Session)
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            var __customer = __customerRepository.GetByName("Prajeesh");
            Assert.IsFalse(NHibernateUtil.IsInitialized(__customer.Orders));

            NHibernateUtil.Initialize(__customer.Orders);
            Assert.IsTrue(NHibernateUtil.IsInitialized(__customer.Orders));

            Assert.IsNotNull(__customer.Orders);
            Assert.IsTrue(__customer.Orders.First().Customer == __customer);
            Assert.IsTrue(__customer.Orders.First().OrderNumber == "2010Jan08CANON_PRA");

            Assert.IsFalse(NHibernateUtil.IsInitialized(__customer.Orders.First().Products));

            NHibernateUtil.Initialize(__customer.Orders.First().Products);
            Assert.IsTrue(NHibernateUtil.IsInitialized(__customer.Orders.First().Products));

            Assert.IsNotNull(__customer.Orders.First().Products);
            Assert.IsTrue(__customer.Orders.First().Products.First().ModelNumber == "SX20 IS");
        }
    }

    [TestMethod]
    public void can_update_orders_for_existing_customer()
    {
        using (ISession __session = SessionManager.CurrentInstance.Session)
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            IProductRepository __productRepository = new ProductRepository(__session);

            var __customer = __customerRepository.First(x => x.FirstName == "Prajeesh");
            var __product = __productRepository.First(x => x.ModelNumber == "SX20 IS");

            var __order = new Order
            {
                Customer = __customer,
                OrderNumber = "2010Jan08CANON_PRA",
                Products = new HashedSet<Product> { __product },
            };

            __customer.Orders = new HashedSet<Order> { __order };
            __customerRepository.Save(__customer);
        }

        using (ISession __session = SessionManager.CurrentInstance.Session)
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            var __customer = __customerRepository.GetByName("Prajeesh");
            Assert.IsFalse(NHibernateUtil.IsInitialized(__customer.Orders));

            NHibernateUtil.Initialize(__customer.Orders);
            Assert.IsTrue(NHibernateUtil.IsInitialized(__customer.Orders));

            Assert.IsNotNull(__customer.Orders);
            Assert.IsTrue(__customer.Orders.First().Customer == __customer);
            Assert.IsTrue(__customer.Orders.First().OrderNumber == "2010Jan08CANON_PRA");

            __customer.Orders.First().OrderNumber = "2010Jan10CANON_PRA";
            __customerRepository.Save(__customer);
            var __savedCustomer = __customerRepository.GetByName("Prajeesh");
            Assert.IsTrue(__customer.Orders.First().OrderNumber == "2010Jan10CANON_PRA");
        }
    }

    [TestMethod]
    public void can_delete_cascade_on_customer()
    {
        using (ISession __session = SessionManager.CurrentInstance.Session)
        {
            ICustomerRepository __customerRepository = new CustomerRepository(__session);
            var __customer = __customerRepository.GetByName("Prajeesh");
            __customerRepository.Remove(__customer);

            IOrderRepository __orderRepository = new OrderRepository(__session);
            var __order = __orderRepository.First(x => x.OrderNumber == "2010Jan08CANON_PRA");
            Assert.IsNull(__order);                
        }
    }

    readonly IEnumerable<Customer> __customerCollection = new List<Customer>
    {
        new Customer {FirstName = "Prajeesh", LastName = "Prathap" },
        new Customer {FirstName = "Steve", LastName = "Roberts" },
        new Customer {FirstName = "Robert", LastName = "Tau" },
        new Customer {FirstName = "Micheal", LastName = "Johnson" }
    };

    readonly IEnumerable<Product> __productCollection = new List<Product>
    {
        new Product { Name="Canon Powershot", ModelNumber="SX20 IS", Amount=399.99M },
        new Product { Name="RIM BlackBerry headset", ModelNumber="HS-655", Amount=25.00M },
        new Product { Name="Dell Laptop", ModelNumber="Studio 17", Amount=1350.45M },
        new Product { Name="Garmin GPS", ModelNumber="nuvi 255WT", Amount=169.99M },
        new Product { Name="Xbox 360 Console", ModelNumber="Arcade Console", Amount=199.99M }
    };

    static ISessionFactory ___sessionFactory;
}

No comments: