There are cases where a set of properties are used repeatedly. These properties may even have their own business logic, but they do not represent an entity in your application. They are value objects. In this recipe, we will tell you how to separate these properties and business logic into a component class without creating a separate entity.
Components
to the MappingRecipes
project.Addr
ess
class with the following properties:public virtual Guid Id { get; protected set; } public virtual string Lines { get; set; } public virtual string City { get; set; } public virtual string State { get; set; } public virtual string ZipCode { get; set; }
Custo
mer
class with the following properties:public virtual string Name { get; set; } public virtual Address BillingAddress { get; set; } public virtual Address ShippingAddress { get; set; }
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MappingRecipes" namespace=" MappingRecipes.Components"> <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" column="BillingLines" /> <property name="City" not-null="true" column="BillingCity" /> <property name="State" not-null="true" column="BillingState" /> <property name ="ZipCode" not-null="true" column="BillingZipCode" /> </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>
Recipe
class:using System; using NH4CookbookHelpers; using NHibernate; namespace MappingRecipes.Components { public class Recipe : HbmMappingRecipe { protected override void AddInitialData(ISession session) { session.Save(new Customer { Name = "Max Weinberg", BillingAddress = new Address { Lines = "E Street 1", City = "Belmar", State = "New Jersey", ZipCode = "123" }, ShippingAddress = new Address { Lines = "Home street", City = "Newark", State = "New Jersey", ZipCode = "123" } }); } public override void RunQueries(ISession session) { var customer = session.QueryOver<Customer>() .SingleOrDefault(); Console.WriteLine( "Customer {0} has a billing address in {1}", customer.Name, customer.BillingAddress.City); } } }
MappingRecipes
application and start the Components
recipe.In this recipe, we can use the Address
component class throughout our model without the overhead of maintaining a separate entity. We have used it in our Customer
class for both billing and shipping address.
Our model looks like this:
We get all the reuse benefits without the database work. The Address
fields are included in every query for Customer
and are automatically loaded.
18.218.212.102