Creating class components

There are cases where a set of properties are used repeatedly. These properties may even have their own business logic, but they don't represent an entity in your application. They are value objects. In this recipe, I'll show you how we can separate these properties and business logic into a component class without creating a separate entity.

How to do it...

  1. Create a new class library project named ComponentExamples.
  2. Add an Address class with the following properties:
    public virtual string Lines { get; set; }
    public virtual string City { get; set; }
    public virtual string State { get; set; }
    public virtual string ZipCode { get; set; }
  3. Add a customer class with the following properties:
    public virtual string Name { get; set; }
    public virtual Address BillingAddress { get; set; }
    public virtual Address ShippingAddress { get; set; }
  4. Add the following mapping document:
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
        assembly="ComponentExamples"
        namespace="ComponentExamples">
      <class name="Customer">
        <id name="Id">
          <generator class="guid.comb" />
        </id>
        <property name="Name" not-null="true" />
        <component name="BillingAddress" class="Address">
          <property name="Lines" not-null="true" />
          <property name="City" not-null="true" />
          <property name="State" not-null="true" />
          <property name ="ZipCode" not-null="true" />
        </component>
        <component name="ShippingAddress" class="Address">
          <property name="Lines" not-null="true" 
                    column="ShippingLines" />
          <property name="City" not-null="true" 
                    column="ShippingCity" />
          <property name="State" not-null="true" 
                    column="ShippingState" />
          <property name ="ZipCode" not-null="true" 
                    column="ShippingZipCode" />
        </component>
      </class>
    </hibernate-mapping>

How it works...

In this recipe, we can use the Address component class throughout our model without the overhead of maintaining a separate entity. We've used it in our Customer class for both billing and shipping address. The resulting database table will appear as shown in the next screenshot:

How it works...

Our model looks like this:

How it works...

We get all the reuse benefits without the database work. The Address fields are included in every query for Customer, and are automatically loaded.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset