Search code examples
c#ormhabanero

How can I enforce a relationship to be compulsory when using SmoothHabanero


I am currently working on a project and have opted to use Habanero as my ORM. I am using SmoothHabanero to set up my business objects. I have a relationship to another class that is required to have at least one object instance to be valid. How would I do this?


Solution

  • OK this could be a bit detailed so let me start with some basics.

    Smooth is a Code First community project for habanero ORM. Smooth is based on a Convention over Configuration approach.

    Your Habanero Domain objects do not need to have a Foreign Key property for it to map correctly to the Database provided that you follow some sort of Convention that Smooth can figure out.

    Typically

    public class Customer : BusinessObject
    {
    }
    public class SalesOrder : BusinessObject
    {
        /// <summary>
        /// The type this SalesOrder is for.
        /// </summary>
        public virtual Customer Customer
        {
            get { return Relationships.GetRelatedObject<Customer>("Customer"); }
            set { Relationships.SetRelatedObject("Customer", value); }
        }
    }
    

    In this scenario the Sales Order has a single relationship to a Customer. The Customer is Compulsory on the Sales Order i.e. the Sales Order cannot be persisted without the Customer being set.

    At a domain level this all makes sense. At a database level however the Customer relationship is mapped using a Foreign Key on the SalesOrder table. If you follow the convention that the CustomerID is the Foreign Key property on the SalesOrder table then this is all you have to do to get the relationship set up in the Domain model and correctly mapped to the Database.

    Now for the answer to your question.

    If the Classes are defined as per the above then all you need to do is add '[AutoMapCompulsory]' attribute and Smooth will do all the necessary setting up of the relationship and its Foreign Key as compulsory for you.

        public class Customer : BusinessObject
    {
    }
    public class SalesOrder : BusinessObject
    {
    
        /// <summary>
        /// The type this SalesOrder is for.
        /// </summary>
        [AutoMapCompulsory]
        public virtual Customer Customer
        {
            get { return Relationships.GetRelatedObject<Customer>("Customer"); }
            set { Relationships.SetRelatedObject("Customer", value); }
        }
    }
    

    Hope this helps brett