tags:

views:

64

answers:

2

I'm working on my first NHibernate project, so this may seem to be a simple question.

The below is simplified from my real scenario to convey the specific question.

Lets say I have a Customer entity

public class Customer
{
    prop virtual int ID { get; set; }
    prop virtual string Name { get; set; }
    prop virtual Region Region { get; set; }
}

and my Region Entity (regions are like, NorthWest, MidWest, etc - a pretty defined list that would be in some sort of drop-down)

public class Region
{
    prop virtual int ID { get; set; }
    prop virtual string Name { get; set; }
    private readonly IList<Customer> _customers = new List<Customer>();

    public virtual void Add(Customer customer)
    {
        _customers.Add(customer);
    }

    public virtual void Remove(Customer customer)
    {
        _customers.Remove(customer);
    }

    public virtual Customer[] GetCustomers()
    {
        return _customers.ToArray();
    }
}

When I go to Persist a Customer Entity, I really only want to have 3 pieces of information (Customer.ID, Customer.Name, & Customer.Region.ID), how do I accomplish this, because NHibernate expects a Customer entity that includes a full Region entity (not just the ID)...

+6  A: 

You can use Load to get the Region by ID without hitting the database. This will give you an entity that NHibernate will recognise and allow you to persist with without the extra database call.

Reference

Garry Shutler
A: 

I think if you already have the ID of the Region, you just have to assign that Id to a new Region object and attach it to your new Customer. As long as you don't have the cascade attribute for that association in the Customer mapping set to "all" or "update" (which would in fact update the data of the existing Region in the DB), it will attach the given Region to the new customer.

El Cheicon