NHibernate listener/event to replace object before insert/update

Posted by vIceBerg on Stack Overflow See other posts from Stack Overflow or by vIceBerg
Published on 2010-12-30T20:49:10Z Indexed on 2010/12/30 20:54 UTC
Read the original article Hit count: 296

Filed under:
|
|

Hi!

I have a Company class which have a collection of Address.

Here's my Address class:(written top of my head):

public class Address
{
  public string Civic;
  public string Street;
  public City City;
}

This is the City class:

public class City
{
  public int Id;
  public string Name;
  public string SearchableName{ get { //code } }
}

Address is persisted in his own table and have a reference to the city's ID. City are also persisted in is own table.

The City's SearchableName is used to prevent some mistakes in the city the user type. For example, if the city name is "Montréal", the searchable name will be "montreal". If the city name is "St. John", the searchable name will be "stjohn", etc.

It's used mainly to to search and to prevent having multiple cities with a typo in it.

When I save an address, I want an listener/event to check if the city is already in the database. If so, cancel the insert and replace the user's city with the database one. I would like the same behavior with updates.

I tried this:

public bool OnPreInsert(PreInsertEvent @event)
{
    City entity = (@event.Entity as City);

    if (entity != null)
    {
        if (entity.Id == 0)
        {
            var city = (from c in @event.Session.Linq<City>()
                        where c.SearchableName == entity.SearchableName
                        select c).SingleOrDefault();
            if (city != null)
            {
                //don't know what to do here
                return true;
            }
        }
    }

    return false;
}

But if there's already a City in the database, I don't know what to do. @event.Entity is readonly, if I set @event.Entity.Id, I get an "null identifier" exception. I tried to trap insert/update on Address and on Company, but the City if the first one to get inserted (it's logic...)

Any thoughts?

Thanks

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about events