Search code examples
nhibernatefluent-nhibernatenhibernate-mapping

nhibernate mapping, map value to key


Lets say I have two tables:

Tasks
  -TaskName
  -CategoryID

Categories
  -ID
  -Name

Now, lets say that I have a class:

Task
  string Name
  string Category   

How do I map this so that when I save a Task object, it will lookup the category id for the given category name and store it in the CategoryID field?

Is it possible to map with Fluent nHibernate?


Solution

  • It is not possible, nor recommended to have a domain Task class designed like that (it is possible to reference the Category by name, but you'd have to store the name instead of the ID in the Task table)

    Instead, you need to separate your public API from your internal domain model:

    class Domain.Task
    {
        //From your description, I'm assuming this is an assigned unique id, even though
        //that's not great either
        public virtual string TaskName { get; set; }
        public virtual Category Category { get; set; }
    }
    
    class Domain.Category
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
    }
    
    class API.Task
    {
        public string Name { get; set; }
        public string Category { get; set; }
    }
    

    And the method that receives the task:

    public void CreateTask(API.Task task)
    {
        session.Save(new Domain.Task
                     {
                         TaskName = task.Name,
                         Category = session.Query<Category>()
                                           .Single(x => x.Name == task.Category)
                     });
    }
    

    The end result is exactly what you want: tasks receive the category by name, and an error is thrown if the category does not exist.