Wednesday, 1 February 2012

Composite key mapping in NHibernate

http://devlicio.us/blogs/anne_epstein/archive/2009/11/20/nhibernate-and-composite-keys.aspx

Create your identifier class...

[Serializable]
public class CategoryProductIdentifier {
        public virtual int ProductId { get; set; }
        public virtual int CategoryId { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
            var t = obj as CategoryProductIdentifier;
            if (t == null)
                return false;
            if (ProductId == t.ProductId && CategoryId == t.CategoryId)
                return true;
            return false;
        }
        public override int GetHashCode()
        {
            return (ProductId + "|" + CategoryId).GetHashCode();
        }
}

Update your existing class to make use of the identifier class

public class CategoryProduct
{
        private CategoryProductIdentifier _categoryProductIdentifier = new CategoryProductIdentifier();
        public virtual CategoryProductIdentifier CategoryProductIdentifier
        {
            get { return _categoryProductIdentifier; }
            set { _categoryProductIdentifier = value; }
        }

        private Product _Product;
        public virtual Product Product
        {
            get { return _Product; }
            set { _Product = value;
                _categoryProductIdentifier.ProductId = _Product.Id; }
        }

        private Category _Category;
        public virtual Category Category
        {
            get { return _Category; }
            set { _Category = value;
                _categoryProductIdentifier.CategoryId = _Category.Id; }
        }
        public virtual string CustomizedProductDescription { get; set; }

}

Change your mapping to make use of the new <composite-id> mapping for the key

 
<hibernate-mapping>
<class name="CategoryProduct" table="CategoryProducts">
    <composite-id name="CategoryProductIdentifier" class="CategoryProductIdentifier">
        <key-property name="ProductId" column="ProductID" type="Int32" />
        <key-property name="CategoryId" column="CategoryID" type="Int32" />
        <version name="LastModifiedOn" type="timestamp" column="LastModifiedOn" />
    </composite-id>
    <many-to-one name="Product" column="ProductID" class="Product" insert="false" update="false" access="field.pascalcase-underscore" />
    <many-to-one name="Category" column="CategoryID" class="Category" insert="false" update="false" access="field.pascalcase-underscore" />
    <property name="CustomizedProductDescription" column="CustomizedProductDesc" />
</class>
</hibernate-mapping>

No comments:

Post a Comment

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...