Positonic
Positonic

Reputation: 9411

fluent nhibernate nullable foreign key "null reference exception"

I have just started with nHibernate Fluent and all is going well with my associations, until I hit a location that have a StateID (which is a foreign key, see below) of null. Then I get an error "null reference exception"

on this line Console.WriteLine(location.address + ", " + location.State.state);

below:

public static void LoadLocationsFromDatabase()
{
    using (var session = NHibernateHelper.OpenSession())
    {
        // retreive all stores and display them
        using (session.BeginTransaction())
        {
            var locations = session.CreateCriteria(typeof(Location))
                .List<Location>();

            var i = 0;
            foreach (var location in locations)
            {
                i++;
                Console.WriteLine(location.address + ", " + location.State.state);
            }
        }

    }
}

public LocationMap()
{
    Id(x => x.locationID).Column("ID");
    Map(x => x.address).Column("Address");
    References(x => x.State)
  .Column("StateID")
      .Cascade.All();
}

public class State
{
    public virtual int ID { get; set; }
    public virtual String state { get; set; }
    public virtual IList<Location> Locations { get; set; }
}

I guess this value might shouldn't probably be null in the DB. StateID is a foreign key to ID on the states table, so I guess it shouldn't be allowed to be null?

Anyway I feel that my code should be able to allow for this one way or another, so how can I get around this?

Upvotes: 1

Views: 1132

Answers (1)

watbywbarif
watbywbarif

Reputation: 6967

Console.WriteLine(location.address + ", " + (location.State == null ? "Unknown" : location.State.state));

Upvotes: 1

Related Questions